Question

I have a code that look like this:

while True:
with open('file', 'r') as file:
    for line in file:
        #Doing something with a different var a each iteration of the while True.

And I'd would like to know if there's a way to restart a "for line" loop at line 0 in order to open the file just once before the beginning of the while true instead of opening it a everytime. Thank you

Was it helpful?

Solution

You don't actually have to restart the loop. You just need to go back to the beginning of the file.

import os

f = open('file', 'r')  # don't use 'file' as a variable name
while True:
    f.seek(0)
    for line in f:
        # do stuff

f.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top