-3
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 am trying to use this but the i value isn't changing at all, what am I doing wrong here? The i value is just saying as -1 for all the lines. Even though it's passing lines that start with 'tmpobjid2a'

Mario
  • 9
  • 5

1 Answers1

-2

You could try

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}]'))
SpghttCd
  • 10,510
  • 2
  • 20
  • 25
  • I used both versions and I ended with 460 with this code. And 457 with the other guy's code. Which one is right? :S – Mario May 05 '19 at 20:09
  • Nevermind, both are the same. THANK YOU BOTH OF YOU – Mario May 05 '19 at 20:12
  • Mario I don't know - this might depend also on your input file. However, regarding downvotes @AndrewAllen should be right, right...:)? – SpghttCd May 05 '19 at 20:15
  • Sorry, I'm trying to do another one but I'm getting the wrong i value... What am I doing wrong? (I edited my question) – Mario May 05 '19 at 20:38
  • Do they _really_ start with `tmpobjid2a` - or are there leading whitespaces? In that case: see my edit. – SpghttCd May 05 '19 at 20:44