问题描述
我关注此主题 here 是因为我想删除输出文本文件中的 <br />
。
所以我的代码如下:
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt','r') as infile,open('comments_'+video_id+'.txt','w') as outfile:
temp = infile.read().replace("<br />","")
outfile.write(temp)
如果我删除这个函数调用,我的文件有内容,但是在我调用这个函数之后,我的文件是空的。我哪里做错了?
解决方法
以 w
模式打开文件首先会截断文件。所以没有什么可以从文件中读取的。
先读取文件,然后打开写入。
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt','r') as infile:
temp = infile.read().replace("<br />","")
with open('comments_'+video_id+'.txt','w') as outfile:
outfile.write(temp)