2 回答

TA貢獻1784條經驗 獲得超7個贊
假設您有一個test.txt包含以下內容的文件:
123,PEN
124,BALL
125,BOOK
126,PENCIL
您可以使用如下代碼,創建一個包含引號內容的臨時文件并替換原始文件:
import os
with open("test.txt") as i: # open file for reading, i = input file
with open("temp.txt", "w") as o: # open temp file in write mode, o = output
for l in i: # read each line
o.write('"{}","{}"\n'.format(l.split(',')[0],l.split(',')[1].split('\n')[0]))
os.remove('test.txt') # remove the old file
os.rename('temp.txt','test.txt') # resave the temp file as the new file
輸出:
"123","PEN"
"124","BALL"
"125","BOOK"
"126","PENCIL"

TA貢獻1890條經驗 獲得超9個贊
我更新了我的答案以涵蓋包含空格的文本的其他情況。
看到你regex的問題中有一個標簽,你可以使用這樣的東西:
import re
text = """123,PEN
124,BALL
125,BOOK
126,PENCIL
123,PEN BOOK"""
new_text = re.sub(r'(\d+),([\w\s]+)$', r'"\1","\2"', text, flags=re.M)
添加回答
舉報