with open('factory2.txt') as sf, open('target1.txt', 'w') as tf:
i = -1
for line in sf:
if line.startswith('tmpobjid2a'):
i += 1
tf.write(line.replace('tmpobjid2a', f'tmpobjid2a[{i}]'))
我正在尝试使用它,但是i值根本没有改变,我在这里做错了什么?对于所有行,i值都表示为-1。即使它以'tmpobjid2a'开头的行通过了
答案 0 :(得分:-2)
您可以尝试
with open(source.txt) as sf, open(target.txt, 'w') as tf:
i = -1
for line in sf:
if line.strip().startswith('alcatrazObj'):
i += 1
tf.write(line.replace('[]', f'[{i}]'))