如何在文件中添加引号

我有下面的文件


123,PEN BOOK

124,BALL

125,BOOK

126,PENCIL BOOK

我需要添加引号


预计出来


"123","PEN BOOK"

"124","BALL"

"125","BOOK"

"126","PENCIL BOOK"


守着星空守着你
浏览 168回答 2
2回答

噜噜哒

假设您有一个test.txt包含以下内容的文件:123,PEN124,BALL125,BOOK126,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 fileos.rename('temp.txt','test.txt')         # resave the temp file as the new file输出:"123","PEN""124","BALL""125","BOOK""126","PENCIL"

当年话下

我更新了我的答案以涵盖包含空格的文本的其他情况。看到你regex的问题中有一个标签,你可以使用这样的东西:import retext = """123,PEN124,BALL125,BOOK126,PENCIL123,PEN BOOK"""new_text = re.sub(r'(\d+),([\w\s]+)$', r'"\1","\2"', text, flags=re.M)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python