Python重置行中的for循环 [英] Python reset line in for loop
本文介绍了Python重置行中的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图重复浏览几行的文本文件.当我的 for 循环完成一次遍历文件后,我想从头开始重复该文件.有什么方法可以重置线路计数器来实现这一目标吗?
I'm trying to repeatedly go through a text file of a few lines. When my for loop is done with one pass through the file, I want to repeat the file from the beginning. Is there any way to reset the line counter to make this happen?
infile=open("some_txt.txt","r")
choice=input("Choice:")
g=0
while choice!="close":
if choice=='1':
take_off=input("Take off:")
for line in infile:
x=line.split()
if x[1]==take_off:
print(x)
g=g+1
if g==0:
print("No match.")
elif choice=='2':
take_off=input("Take off 2:")
for line in infile:
x=line.split()
if x[2]==take_off:
print(x)
g=g+1
if g==0:
print("No match.")
choice=input("Choice")
推荐答案
我收集到您想返回到文件开头并再次读取所有内容的信息.最简单的方法是
I gather that you want to go back to the start of the file and read it all again. The simplest way is
infile.seek(0)
infile.seek(0)
一种更慢,更复杂的方法是关闭文件并重新打开.
A slower and somewhat more involved way is to close the file and reopen it.
这篇关于Python重置行中的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文