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

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
    file.close()

for loop in range(5):
    with open('somefile.txt') as fin:
        for line in fin:
            print(fin)

This will re-open the file five times. You could seek() to beginning instead, if you like.

Tags:

Python