gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:15 26 4
gpt4 key购买 nike

我的代码如下所示:

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

关于python - 在 python 中的 "For line"语句的第 0 行重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23148996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com