[英]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:通常这可以使用 bash 和 sed 来完成:
sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt> outputfile.txt
I want to implement it from python using subprocess.call()我想使用 subprocess.call() 从 python 实现它
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.我想我必须先创建文件 outputfile.txt,但我想从 python 中完成这一切。 Can you help me please, thanks in advance.你能帮我吗,在此先感谢。
To use >
redirection you need to use shell=True
and a single string argument, not a list.要使用>
重定向,您需要使用shell=True
和单个字符串参数,而不是列表。
subprocess.call("""sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt > outputfile.txt""", shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.