Python 3.x 为什么此子流程命令不起作用?
我试图删除多个Python 3.x 为什么此子流程命令不起作用?,python-3.x,subprocess,Python 3.x,Subprocess,我试图删除多个txt文件中每行的第一个和最后一个逗号。当我运行下面的脚本时,_文件中的都没有更改(即逗号仍然存在)。我错过了什么?有更好的方法吗 我从中找到了rev命令 我的脚本 import subprocess from glob import glob in_files = glob('path/to/files/*.txt') for fyle in in_files: rr = f"rev {fyle} | cut -c2- | rev | cut -c2-" su
txt
文件中每行的第一个和最后一个逗号。当我运行下面的脚本时,_文件中的都没有更改(即逗号仍然存在)。我错过了什么?有更好的方法吗
我从中找到了rev
命令
我的脚本
import subprocess
from glob import glob
in_files = glob('path/to/files/*.txt')
for fyle in in_files:
rr = f"rev {fyle} | cut -c2- | rev | cut -c2-"
subprocess.check_output(['bash', '-c', rr])
,-0.12000000000000000,0.0000000000000000,
,-0.11889999999999999,0.0000000000000000,
,-0.11780000000000000,0.0000000000000000,
,-0.11670000000000000,0.0000000000000000,
,-0.11559999999999999,0.0000000000000000,
,-0.11449999999999999,0.0000000000000000,
文件(file1.txt)
预期的
-0.12000000000000000,0.0000000000000000
-0.11889999999999999,0.0000000000000000
-0.11780000000000000,0.0000000000000000
-0.11670000000000000,0.0000000000000000
-0.11559999999999999,0.0000000000000000
-0.11449999999999999,0.0000000000000000
您是否需要使用外部程序,或者这是否适合您的需要
def trim(filename, new_filename):
with open(filename) as infile:
with open(new_filename, "w") as outfile:
for line in infile:
outfile.write(line.strip(",\n") + "\n")
file_list = ["file1.txt"]
for f in file_list:
# btw if you want the original file to
# be overwritten, call `trim(f, f)`
trim(f, f+"_new.txt")
这会将您预期的输出写入文件。为什么这会被否决?这很有效,谢谢,但我仍然想知道为什么我的subprocess命令不起作用。