我正在尝试运行一个Python脚本,该脚本接收一个输入文件,操纵它的内容并将结果写入输出文件。
我想在每一行都用引号引起来。 目前,我在下面创建了脚本。
import sys
import re
inFile = sys.argv[1]
outFile = sys.argv[2]
with open(inFile,'r') as i:
lines = i.readlines()
def manipulate_data(lines):
content = [x.rstrip('\n') for x in lines]
res = [re.sub(r"(.+)", r"'\g<0>',", y) for y in content]
return res
processedLines = manipulate_data(lines)
with open(outFile,'w') as o:
for line in processedLines:
o.write(line)
我用python3 script.py input.txt output.txt
它运行,但是我希望更改它,以便它逐行写入输出文件。我也觉得我不必要两次使用[do_something for something in somethings]
。
我如何达到我想要的结果?
答案 0 :(得分:1)
您可以一次性读取一个文件中的行,修改并写入另一个文件:
with open(inFile, 'r') as inf, open(outFile, 'w') as outf:
for line in inf:
outf.write('"{}"\n'.format(line.strip('\n')))
答案 1 :(得分:1)
您只需在读取文件时进行字符串格式化并将更新后的字符串写入外文件中即可!
with open(inFile,'r') as f, open(outFile,'w') as w:
for line in f.readlines():
w.write("'%s'\n" % line.rstrip('\n'))