我有一个包含非法字符的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()这会给我一个坏的文件描述符错误。
如何对同一文件进行读写?
谢谢
发布于 2011-06-14 04:04:46
一直附加到文件末尾的原因是,您需要查找到文件的开头,以便将行写出。
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.(我自己决定只使用上下文管理器语法。)
发布于 2011-06-14 04:02:19
你可以用writeline函数重写行列表。
with open(filename, "r") as f:
lines = f.readlines()
#edit lines here
with open(filename, "w") as f:
f.writelines(lines)https://stackoverflow.com/questions/6335624
复制相似问题