Skip to content
Advertisement

Python dynamic for loop range size

I’m trying to add Link argument to ini file by using python. Example of ini file:

[sometag]
sometext
sometext
sometext

[sometag2]
sometext2
sometext2
sometext2

[sometag3]
sometext3
sometext3
sometext3

I need to do like this:

[sometag]
sometext
sometext
sometext

Link = [sometag]

[sometag2]
sometext2
sometext2
sometext2

Link = [sometag2]
...

My for loop:

for i in range(len(m)):
    if m[i] in t:
        for j in xrange(i, len(m)):
            if len(m[j].strip()) == 0 and m[j+1].startswith('['):
                m.insert(j, Link.....
                break


# m = ini_file.readlines()
# t = ['[sometag]', '[sometag2]']

My code works, but it does not add Link for last tags. I’ve found why. If I add in range(len(m)+100): Then code adds all Links.

Looks like len(m) is old value (static?), because I’m increasing len with insert during loop. Any ideas?

I have tried something like insertings = 0, then range(len(m)+insertings) and afer insert insertings = insertings+1 But no luck :(

Advertisement

Answer

Create a new list:

new = []
tag = None
for line in m:
    if line.startswith('['):
        if tag:
            new.append('Link = ' + tag)
        tag = line
    new.append(line)
Advertisement