读写文件
我有一个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()
结果却出现了一个“坏文件描述符”的错误。
我该如何在同一个文件中进行读写操作呢?
谢谢
2 个回答
2
你可以用writelines这个函数来重新写入行的列表。
with open(filename, "r") as f:
lines = f.readlines()
#edit lines here
with open(filename, "w") as f:
f.writelines(lines)
0
你一直在文件的末尾添加内容,是因为你需要先把光标移动到文件的开头,才能把你的内容写进去。
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.
(我决定自己使用上下文管理器的写法。)