Home > Software design >  Replace strings and update file using sed from python
Replace strings and update file using sed from python

Time:12-14

Im trying to replace the first line of a file which has double quotes. The File contains something like this:

"A"|"B"|"C"
"1"|"2"|"3"

I want to create or update the file to show something as follows (first line without double quotes):

A|B|C
"1"|"2"|"3"

Typically this can be done using bash with sed:

sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt> outputfile.txt

I want to implement it from python using subprocess.call()

My code:

subprocess.call(["sed", 's/"A"|"B"|"C"/A|B|C/g', "inputfile.txt", ">", "outputfile.txt"])

But it throws an error:

sed: can't read >: No such file or directory
sed: can't read outputfile.txt: No such file or directory

I guess I have to create the file outputfile.txt first, but i want to do it all from python. Can you help me please, thanks in advance.

CodePudding user response:

To use > redirection you need to use shell=True and a single string argument, not a list.

subprocess.call("""sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt > outputfile.txt""", shell=True)
  • Related