Search and replace a line in a file in Python(在 Python 中搜索和替换文件中的一行)
问题描述
我想遍历文本文件的内容并在某些行上进行搜索和替换,然后将结果写回文件.我可以先将整个文件加载到内存中,然后再将其写回,但这可能不是最好的方法.
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
在以下代码中最好的方法是什么?
What is the best way to do this, within the following code?
推荐答案
我想应该这样做.它基本上将内容写入新文件并用新文件替换旧文件:
I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:
这篇关于在 Python 中搜索和替换文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!