Python for循环中的重置行

New*_*bie 0 python for-loop line reset

我试图反复浏览几行文本文件.当我的for循环完成一遍文件后,我想从头开始重复该文件.有没有办法重置线计数器来实现这一目标?

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")
Run Code Online (Sandbox Code Playgroud)

Pru*_*une 5

我想你想回到文件的开头再读一遍.最简单的方法是

infile.seek(0)

更慢且更复杂的方法是关闭文件并重新打开它.