Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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 = 0while loops < 5:
    file = open("somefile.txt")
    for line in file:
        print(line)
    loops = loops + 1
    file.close()

Solution 2:

for loop inrange(5):
    withopen('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.

Solution 3:

for line in file reads each line once. If you want to start over from the first line, you could for example close and reopen the file.

Solution 4:

Python file objects are iterators. Like other iterators, they can only be iterated on once before becoming exhausted. Trying to iterate again results in the iterator raising StopIteration (the signal it has nothing left to yield) immediately.

That said, file objects do let you cheat a bit. Unlike most other iterators, you can rewind them using their seek method. Then you can iterate their contents again.

Another option would be to reopen the file each time you need to iterate on it. This is simple enough, but (ignoring the OS's disk cache) it might be a bit wasteful to read the file repeatedly.

A final option would be to read the whole contents of the file into a list at the start of the program and then do the iteration over the list instead of over the file directly. This is probably the most efficient option as long as the file is small enough that fitting its whole contents in memory at one time is not a problem.

Solution 5:

when you iterate once the pointer points to the last line in the file so try to use file.seek(0) instead of opening the file again and again in the loop

withopen('a.txt','r+')as f:
        for i inrange(0,5):
            for line in f:
                print(line)
            f.seek(0)

Post a Comment for "Python Refuses To Iterate Through Lines In A File More Than Once"