读写文件

| 我有一个包含非法字符的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)
    

要回复问题请先登录注册