使用来自 python 的 sed 替换字符串和更新文件
Replace strings and update file using sed from python
我正在尝试替换带有双引号的文件的第一行。
该文件包含如下内容:
"A"|"B"|"C"
"1"|"2"|"3"
我想创建或更新文件以显示如下内容(第一行不带双引号):
A|B|C
"1"|"2"|"3"
通常这可以使用 bash 和 sed:
来完成
sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt> outputfile.txt
我想从 python 使用 subprocess.call()
实现它
我的代码:
subprocess.call(["sed", 's/"A"|"B"|"C"/A|B|C/g', "inputfile.txt", ">", "outputfile.txt"])
但它抛出一个错误:
sed: can't read >: No such file or directory
sed: can't read outputfile.txt: No such file or directory
我想我必须先创建文件 outputfile.txt,但我想全部从 python 开始。
你能帮我吗,先谢谢了。
要使用 >
重定向,您需要使用 shell=True
和单个字符串参数,而不是列表。
subprocess.call("""sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt > outputfile.txt""", shell=True)
我正在尝试替换带有双引号的文件的第一行。 该文件包含如下内容:
"A"|"B"|"C"
"1"|"2"|"3"
我想创建或更新文件以显示如下内容(第一行不带双引号):
A|B|C
"1"|"2"|"3"
通常这可以使用 bash 和 sed:
来完成sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt> outputfile.txt
我想从 python 使用 subprocess.call()
实现它我的代码:
subprocess.call(["sed", 's/"A"|"B"|"C"/A|B|C/g', "inputfile.txt", ">", "outputfile.txt"])
但它抛出一个错误:
sed: can't read >: No such file or directory
sed: can't read outputfile.txt: No such file or directory
我想我必须先创建文件 outputfile.txt,但我想全部从 python 开始。 你能帮我吗,先谢谢了。
要使用 >
重定向,您需要使用 shell=True
和单个字符串参数,而不是列表。
subprocess.call("""sed 's/"A"|"B"|"C"/A|B|C/g' inputfile.txt > outputfile.txt""", shell=True)