python - 如何增量更改文件中的字符串?
问题描述
我需要搜索一个文件,并更改每次出现的字符串。但是,每次我更改字符串时,它都需要稍有不同。
例如,我想在文件中查找“foo”。第一次找到,想改成“bar1”。下次我找到它时,我想将其更改为“bar2”等
最好的方法是什么?
谢谢你。
解决方案
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)
推荐阅读
- anylogic - 我想从点转换为代理,这给了我正确的位置
- ffmpeg - ffmpeg可以在windows中自己创建文件夹吗?
- c# - 如何合并两个文本?
- tensorflow - 如何使用 Tensorflow 检测图像中是否缺少对象?
- java - 如果我通过 phpMyAdmin 执行我的查询,它可以工作,而它不在我的 java 程序中
- python - 为什么我的 if 语句在 python 中不起作用?
- angular - 如何在 Angular 7 中使 asyn 像 ajax 一样为假
- android - 无法运行 react-native run-android
- python-3.x - 如何通过在 python 中导入 excel 数据在 SQLite3 中创建表?
- angular - Angular cdk Drap and drop 在搜索功能期间无法按预期工作