[英]Python script that surrounds each line in file with apostrophe
我正在嘗試運行一個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]
。
我怎樣才能達到理想的效果?
您可以一次性讀取一個文件中的行,修改並寫入另一個文件:
with open(inFile, 'r') as inf, open(outFile, 'w') as outf:
for line in inf:
outf.write('"{}"\n'.format(line.strip('\n')))
您可以在讀取文件時簡單地進行字符串格式化,並將更新后的字符串寫入輸出文件!
with open(inFile,'r') as f, open(outFile,'w') as w:
for line in f.readlines():
w.write("'%s'\n" % line.rstrip('\n'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.