我正在尝试删除多个txt
文件的每一行中的第一个和最后一个逗号。当我运行以下脚本时,in_files
的所有内容均未更改(即逗号仍然存在)。我想念什么?有更好的方法吗?
我从rev
找到了this thread命令。
我的脚本
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])
in_files(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,
期望
-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")
这会将您的预期输出写入文件。