【发布时间】:2010-09-07 12:49:06
【问题描述】:
我想遍历文本文件的内容并在某些行上进行搜索和替换,然后将结果写回文件。我可以先将整个文件加载到内存中,然后再将其写回,但这可能不是最好的方法。
在以下代码中最好的方法是什么?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
【问题讨论】: