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)
添加回答
举报