使用While循环而不是For迭代文件

时间:2017-11-20 21:36:43

标签: python python-3.x

我正在使用Python 3并希望将某些内容转换为while循环,但我是新手,所以我遇到了一些麻烦。

username_chosen = input("Enter the username of the user for their details :")
with open("data.txt") as f:
    for line in f:
        if username_chosen in line:
            print(line)

我想要的循环是程序一直在检查是否有用户输入的用户名,如果没有,那么它会告诉他们错误并提示他们再次输入,直到程序找到用户名。

2 个答案:

答案 0 :(得分:0)

不是您正在寻找的确切答案,但我认为递归是解决此问题的更酷/更优雅的方法。看看这个:

def look_for_username(f):
    username_chosen = input("Enter the username of the user for their 
        details: ")

    for line in f:
        if username_chosen in line:
            print(line + '\nSUCCESS!')
            return

    print('No such username in file')
    f.seek(0)
    return look_for_username(f)


with open('user_data.txt', 'rt') as file:
    look_for_username(file)

因此,如果username_chosen不在line中,那么我们会使用f.seek(0)移回文件的第一行,然后我们再次调用look_for_username。像这样使用递归的唯一问题是python只允许输入999个不正确的用户名。

答案 1 :(得分:-1)

我很惊讶没有人建议:

with open("data.txt") as f:
    lines = tuple(line.strip() for line in f) #strip() the newline at the end of each line

while True:
    username_chosen = input("Enter the username of the user for their details :")

    #This condition will do what you have right now.
    if any((username_chosen in line) for line in lines):
    #The following will require the username to exactly match one of the lines in the file
    #if username_chosen in lines:
        break

    print("Invalid username") #Error message

是的,如果你有大量的用户名,那么这是内存效率低下的。在这种情况下,其中一个答案可能是你最好的选择。

是的,我保留了OP的用户名检查算法,正如一些人所指出的那样,这种算法存在缺陷。如果您不想这样,请取消注释另一个if语句。

相关问题