Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 271
Dan Fiscus Avatar asked Oct 01 '17 01:10

Dan Fiscus


3 Answers

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()
like image 73
charlesreid1 Avatar answered Oct 28 '22 11:10

charlesreid1


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.

like image 25
J_H Avatar answered Oct 28 '22 09:10

J_H


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.

like image 42
Chris Johnson Avatar answered Oct 28 '22 11:10

Chris Johnson