读取和写入文件

时间:2011-06-13 19:59:24

标签: python file-io

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

答案 0 :(得分:2)

您可以使用writelines函数重写行列表。

with open(filename, "r") as f:

    lines = f.readlines()

#edit lines here

with open(filename, "w") as f:

    f.writelines(lines)

答案 1 :(得分: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.

(决定自己只使用上下文管理器语法。)