Skip to main content
 首页 » 编程设计

python之在 python 中的 "For line"语句的第 0 行重新启动

2025年05月04日9qq78292959

我的代码如下所示:

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()