问题描述
我创建了一个 txt 文件,但我没有转到下一行,而是将 \n
附加到下一个单词。例如:
'Title_lower_case\npropane certified\nfuel yard technician\nlaw enforcement graduated\ndeveloperator seeks interesting\nquinn contracting\nhaleybradley\ni\'m out here\nsupervisor; business owner\ninternational business dvelopment\noscar\nhealthcare advocates\nst.catharines\noperations assistant at foreign links around the globe\npipeline management\nseasoned health care professional\nspecializing the human side\nexecutive social media\ncaring individual.\nor research work upon return from u.s peautomated courseexchange corps volunteer service may of\nprofesional cook\npsychological ass
如何将所有 \n
更改为 ,
?
解决方法
这将是您问题的简单版本,假设 test.txt
是您的文本文件:
with open('test.txt','r') as f1:
new_txt = f1.read().replace(r'\n',',')
with open('test.txt','w') as f2:
f2.write(new_txt)
,
这段代码可以解决问题(不需要额外的模块):
with open("file.txt","r") as f: #Read the file
text = f.read()
print(text)
text = text.replace("\\n",",") #replace the unwanted string
print(text)
with open("file.txt","w") as f: #Rewrite the old file
f.write(text)