psmith
psmith

Reputation: 1813

Loop over the list many times

Let's say I have a file source.txt containing a few rows. I want to print rows over and over until I break the program manually.

file_source = 'source.txt'
source = open(file_source,'r')

while 1:
    for line in source:
        print line

source.close()     

The easiest solution is fut open and close into while loop. By my feeling is that's not the best solution.

Can you suggest something better? How to loop over variable source many times?

Regards

Upvotes: 0

Views: 50

Answers (2)

AKS
AKS

Reputation: 19811

You can read the lines at first and save them into a list. So your file is closed after reading. Then you can proceed with your infinite loop:

lines = []

with open(file_source, 'rb') as f:
    lines = f.readlines()

while 1:
    for line in lines:
        print line

But, this is not advised if your file is very large since everything from the file will be read into the memory:

file.readlines([sizehint]):

Read until EOF using readline() and return a list containing the lines thus read.

Upvotes: 1

larsks
larsks

Reputation: 311506

I wasn't sure this would work, but it appears you can just seek to the beginning of the file and then continue iterating:

file_source = 'source.txt'
source = open(file_source,'r')

while 1:
    for line in source:
        print line
    source.seek(0)

source.close()     

And obviously if the file is small you could simply read the whole thing into a list in memory and iterate over that instead.

Upvotes: 4

Related Questions