首页 > 解决方案 > 如何增量更改文件中的字符串?

问题描述

我需要搜索一个文件,并更改每次出现的字符串。但是,每次我更改字符串时,它都需要稍有不同。

例如,我想在文件中查找“foo”。第一次找到,想改成“bar1”。下次我找到它时,我想将其更改为“bar2”等

最好的方法是什么?

谢谢你。

标签: python

解决方案


I think following code should do what you want:

def replace_incrementally(file, to_replace, replace_with)
    with open(file, 'r') as f:
        new_lines = []
        counter = 0
        for line in f.readlines():
            res = [i for i in range(len(line)) if line.startswith(to_replace, i)] 
            for i in range(len(res)):
                line.replace(to_replace+"".format(counter), replace_with, 1)
                counter += 1
            new_lines.append(line)

    with open(file, 'w') as f:
        f.writelines(new_lines)

推荐阅读