在Python中搜索并替换文件中的一行
我想循环一个文本文件的内容,并在一些行上进行搜索和替换,并将结果写回该文件。我可以先在内存中加载整个文件,然后将其写回去,但这可能不是最好的方法。
在下面的代码中,最好的方法是什么?
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
慕盖茨4494581
浮云间
相关分类