读取文件 - 修改内容 - 写入同一文件

23 投票
2 回答
38868 浏览
提问于 2025-04-17 00:21

我需要读取一个文件,修改文件中的某些文本部分,然后再把它写回到同一个文件里。

现在我做的步骤是:

f = open(file)
file_str = f.read() # read it in as a string, Not line by line
f.close()
#
# do_actions_on_file_str
#
f = open(file, 'w') # to clear the file
f.write(file_str)
f.close()

不过我觉得应该有一种更符合Python风格的方法,也能得到同样的结果。

有什么建议吗?

2 个回答

5

如果你想逐行处理文件,可以使用fileinput这个库,并开启“就地”模式。

import fileinput

for line in fileinput.input(mifile, inplace=1):
    print process(line)

如果你需要一次性处理所有文本,那么可以使用with来优化你的代码,这样可以自动帮你关闭文件:

with open(myfile) as f:
    file_str = f.read()
#
do_actions_on_file_str
#
with open(myfile, 'w') as f:
    f.write(file_str)
28

这看起来很简单,也很清楚。任何建议都要看文件的大小。如果文件不大,那就没问题。如果文件很大,你可以分块处理。

不过,你可以使用上下文管理器,这样就不需要手动关闭文件了。

with open(filename) as f:
    file_str = f.read()

# do stuff with file_str

with open(filename, "w") as f:
    f.write(file_str)

撰写回答