关于python:我如何从一个外部文件中读取一个列表,这样当我输入一个用户名时,如果它在这个外部文件中,一个真正的值就会被打印出来?

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输入为用户名,则输出应为"请输入密码"


lines = f.readlines()将创建文本文件中每行的列表。前提是每个用户名位于单独的行上。否则,您不想一行一行地读取它,而是需要一些其他分隔符。

您要做的是检查用户名输入是否在该列表中。所以你想要:

1
if username in lines:

但问题是,它需要精确匹配。如果有多余的空白,它将失败。因此,您可以使用.strip()清除任何空白。

还有一个巨大的问题:

1
print = input("Please enter your password")

您正在使用print函数存储输入字符串。当你使用input时,它会打印出来。然后你真正想要的是将输入存储为某种东西…我称之为password

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")