Dan Fiscus Dan Fiscus - 3 years ago 183
Python Question

Python refuses to iterate through lines in a file more than once

I am writing a program that requires me to iterate through each line of a file multiple times:

loops = 0
file = open("somefile.txt")
while loops < 5:
for line in file:
print(line)
loops = loops + 1


For the sake of brevity, I am assuming that I always need to loop through a file and print each line 5 times. That code has the same issue as the longer version I have implemented in my program: the file is only iterated through one time. After that the
print(line)
file does nothing. Why is this?

Answer Source

It's because the file = open("somefile.txt") line occurs only once, before the loop. This creates one cursor pointing to one location in the file, so when you reach the end of the first loop, the cursor is at the end of the file. Move it into the loop:

loops = 0
while loops < 5:
    file = open("somefile.txt")
    for line in file:
        print(line)
    loops = loops + 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download