2 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
假設(shè)您有一個(gè)test.txt包含以下內(nèi)容的文件:
123,PEN
124,BALL
125,BOOK
126,PENCIL
您可以使用如下代碼,創(chuàng)建一個(gè)包含引號(hào)內(nèi)容的臨時(shí)文件并替換原始文件:
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貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
我更新了我的答案以涵蓋包含空格的文本的其他情況。
看到你regex的問(wèn)題中有一個(gè)標(biāo)簽,你可以使用這樣的東西:
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)
添加回答
舉報(bào)