我正在使用Python 3.6.3。
我正在尝试从csv文件验证用户名和密码。用户名和后续密码在文本文件中的新行上,因此当附加到我称为“up”的空数组时,它被转换为2d数组,每行都有一个列表在“up”中。我要求用户输入用户名和密码。那么我尝试使用for循环( for x in up )通过 up [up.index(x)] 循环遍历每个列表,然后使用 .index(用户名)直接在一个名为j的变量( j = up [up.index(x)]。index(username))中。代码将被给出,我突出显示的部分有问题。 这些是csv文件的内容:Text File
当我运行代码时,它会返回一个错误,指出 用户名不在列表中。 我搜索了答案但找不到任何内容。有什么东西我忽略了吗?
感谢任何帮助。
import csv
validoption = ["i","u"]
while True:
option = input("Sign in or sign up\nPlease enter 'i' to sign in or 'u' to sign up: ")
if option in validoption:
if option is "i":
with open("login.txt","r") as l:
up = []
read = csv.reader(l)
count = 0
for line in read:
up.append(line)
count=+1
invalid = True
while invalid:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if [[y is username for y in x] for x in up]:
for x in up:
j = up[up.index(x)].index(username)
if password in up[up.index(x)][j+1]:
invalid = False
else:
print("Password is incorrect")
else:
print("Username is not recognised")
else:
with open("login.txt","a") as l:
username = input("Please enter your username: ")
while True:
password = input("Please enter your password\nPlease make sure that your password is longer than 8 characters, has a capiatal letter and a number: ")
if len(password)<8:
if any(p.isupper() for p in password):
if any(p.isdigit() for p in password):
break
else:
print("Password must have one number in it\n")
else:
print("Password must have one capital letter\n")
else:
print("Password must have more than 8 charaters")
userdetails = username+","+password
l.write(userdetails)
l.write("\n")
谢谢:)
答案 0 :(得分:0)
y is username
测试两个值是否为相同的对象,而不是等效对象。请改用==
。
此外,您应该考虑使用用户名作为dict
的密钥,然后您可以使用in
并消除应用程序代码中的某些循环。