如何解决读写文件
| 我有一个包含非法字符的XML文件,正在浏览文件,从所有行中删除该字符并将这些行存储在列表中。我现在想将这些相同的行写回到文件中,并覆盖已经存在的内容。 我尝试了这个:file = open(filename,\"r+\")
#do stuff
只是将结果附加到文件末尾,我想覆盖现有文件。
还有这个:
file = open(filename,\"r\")
#read from the file
file.close()
file = open(filename,\"w\")
#write to file
file.close()
这给了我一个错误的文件描述符错误。
我如何读写同一文件?
谢谢
解决方法
始终将文件末尾附加到文件末尾的原因是,您需要搜索文件的开头以写出行。
with open(filename,\"r+\") as file:
lines = file.readlines()
lines = [line.replace(bad_character,\'\') for line in lines]
file.seek(0)
file.writelines(lines)
file.truncate() # Will get rid of any excess characters left at the end of the file due to the length of your new file being shorter than the old one,as you\'ve removed characters.
(决定自己使用上下文管理器语法。)
, 您可以使用writelines函数重新编写行列表。
with open(filename,\"r\") as f:
lines = f.readlines()
#edit lines here
with open(filename,\"w\") as f:
f.writelines(lines)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。