简体   繁体   English

For循环似乎只运行一次

[英]For loop seems to only run once

I have built, as part of a project, a very simple program that checks whether or not a given string is present in a provided text file.作为项目的一部分,我构建了一个非常简单的程序,用于检查给定字符串是否存在于提供的文本文件中。

The program checks if the input is equal to each line of the file, using a for loop, and returns True if the values correspond, False if the don't.程序使用for循环检查输入是否等于文件的每一行,如果值对应则返回 True,否则返回 False。

with open (names, "r") as file:
    while True: 
        name_check = input("name: ")
        if name_check == "":
            #command to end the program

            break
        for newline in file:
            #compares the input with every line in the txt file

            newline_stripped = newline.lower().strip()
            if newline_stripped == name_check:         

                print (True)
            else:
                print (False)
    file.close()

The issue is, when i run the code, the first iteration works fine, it returns a sequence of False and True as intended, and then asks for another input, however when said input is given again, it immediately asks for another one, without returning any sequence, as if the for loop is being skipped entirely.问题是,当我运行代码时,第一次迭代工作正常,它按预期返回一个 False 和 True 序列,然后要求另一个输入,但是当再次给出所述输入时,它立即要求另一个输入,没有返回任何序列,就好像完全跳过了for循环一样。

I tried running it by using a list of numbers instead of a text file as a source (with proper modification) and it runs 100% as intended, so I suspect it has something to do the way it handles the file itself, but I can't figure out why.我尝试通过使用数字列表而不是文本文件作为源(经过适当修改)来运行它,并且它按预期运行 100%,所以我怀疑它与处理文件本身的方式有关,但我可以不知道为什么。

Thanks in advance for any help!提前感谢您的帮助!

You walk through the entire file on the first iteration, so the second iteration has nothing left to read.您在第一次迭代时遍历整个文件,因此第二次迭代没有任何内容可供阅读。 You can either open the file on each iteration, or move the position to the start by file.seek(0) .您可以在每次迭代时打开文件,也可以通过file.seek(0)将 position 移至开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM