문제

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

도움이 되었습니까?

해결책

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()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top