我有一个代码如下:
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.
我想知道是否有办法在第0行重新启动"for line"循环,以便在while true开始之前只打开一次文件,而不是每次都打开一次。感谢
您实际上不必重新启动循环。你只需要回到文件的开头。
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()