C.G. C.G. - 3 months ago 8
Python Question

Python: Using readine() in "for line in file:" Loop

Lets say I have a text file that looks like:

a
b
start_flag
c
d
e
end_flag
f
g


I wish to iterate over this data line by line, but when I encounter a 'start_flag', I want to iterate until I reach an 'end_flag' and count the number of lines in between:

newline = ''
for line in f:
count = 0
if 'start_flag' in line:
while 'end_flag' not in newline:
count += 1
newline = f.readline()
print(str(count))


What is the expected behavior of this code? Will it iterate like:

a
b
start_flag
c
d
e
end_flag
f
g


Or:

a
b
start_flag
c
d
e
end_flag
c
d
e
end_flag
f
g

Answer

There shouldn't be any need to use readline(). Try it like this:

with open(path, 'r') as f:
    count = 0
    counting = False
    for line in f:
        if 'start_flag' in line:
            counting = True
        elif 'end_flag' in line:
            counting = False
            #do something with your count result
            count = 0 #reset it for the next start_flag
        if counting is True:
            count += 1

This handles it all with the if statements in the correct order, allowing you to just run sequentially through the file in one go. You could obviously add more operations into this, and do things with the results, for example appending them to a list if you expect to run into multiple start and end flags.