相关疑难解决方法(0)

在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
Run Code Online (Sandbox Code Playgroud)

python file

271
推荐指数
11
解决办法
42万
查看次数

标签 统计

file ×1

python ×1