How can I read a list from an external file so that when I input a username if it is on that external file a true value will print?
我输入一个用户名-"user1"-但是结果总是显示"user1"是一个错误的用户名,即使它在外部文本文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import random print ("Welcome to the Music Quiz!") username = input("please enter your Username...") f = open("F:/GCSE/Computer Science/Programming/username.txt","r"); lines = f.readlines() if username =="lines": print = input("Please enter your password") else: print("That is an incorrect username") |
如果用户名-用户1用户2用户3用户4用户5输入为用户名,则输出应为"请输入密码"
您要做的是检查用户名输入是否在该列表中。所以你想要:
1 | if username in lines: |
但问题是,它需要精确匹配。如果有多余的空白,它将失败。因此,您可以使用
还有一个巨大的问题:
1 | print = input("Please enter your password") |
您正在使用print函数存储输入字符串。当你使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import random print ("Welcome to the Music Quiz!") username = input("please enter your Username...") f = open("C:/username.txt","r") # Creates a list. Each item in the list is a string of each line in your text files. It is stored in the variable lines lines = f.readlines() # the strings in your list (called lines), also contains escape charachters and whitespace. So this will create a new list, and for each string in the lines list will strip off white space before and after the string users = [user.strip() for user in lines ] # checks to see if the username input is also in the users list if username in users: password = input("Please enter your password:") else: print("That is an incorrect username") |