Pregunta

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

¿Fue útil?

Solución

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()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top