Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace strings and update file using sed from python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading