Python 从文件创建列表时,如果文件包含多个值,它将无法识别任何值
我制作了一个程序,应该从文件中获取用户名和密码列表。如果文件只有一个用户名和密码,它就可以完美地工作,但一旦我包含了多个用户名和密码,它就根本无法识别它们。下面是代码Python 从文件创建列表时,如果文件包含多个值,它将无法识别任何值,python,Python,我制作了一个程序,应该从文件中获取用户名和密码列表。如果文件只有一个用户名和密码,它就可以完美地工作,但一旦我包含了多个用户名和密码,它就根本无法识别它们。下面是代码 import easygui as e import os upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] lower = ["a","b","c","
import easygui as e
import os
upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
loginsystem = True
while loginsystem == True:
users = []
file = open("users.secure","r")
reading = True
while reading == True:
tempuser = file.readline()
if tempuser == "":
reading = False
else:
users.append(tempuser)
file.close()
passwords = []
file = open("passwords.secure","r")
reading = True
while reading == True:
temppassword = file.readline()
if temppassword == "":
reading = False
else:
passwords.append(temppassword)
file.close()
loginmsg = "Enter your username and password"
logintitle = "Login"
loginfieldnames = ["Username","Password"]
loginfieldvalues = []
login = True
while login == True:
loginfieldvalues =
e.multpasswordbox(loginmsg,logintitle,loginfieldnames)
while 1:
if loginfieldvalues == None: break
loginerrmsg = ""
for i in range(len(loginfieldnames)):
if loginfieldvalues[i].strip() == "":
loginerrmsg = loginerrmsg + ('"%s" is a required field.\n\n' % loginfieldnames[i])
if loginerrmsg == "": break
loginfieldvalues = e.multpasswordbox(loginerrmsg, logintitle, loginfieldnames, loginfieldvalues)
inputuser = loginfieldvalues[0]
inputpassword = loginfieldvalues[1]
if inputuser not in users:
e.msgbox("Unknown username.",title="Login",ok_button="Try Again")
else:
placement = users.index(inputuser)
if inputpassword != passwords[placement]:
e.msgbox("Invalid password.",title="Login",ok_button="Try Again")
else: login = False
e.msgbox("Welcome, " + inputuser,title="Login System",ok_button="Continue")
basicoptions = ["Logout","Quit"]
running = True
while running == True:
choice = e.buttonbox("What would you like to do?",title="Login System",choices=basicoptions)
if choice == "Quit":
os._exit(0)
else:
running = False
这些文件只包含单词“admin”,当我添加另一个值时,在写入文件时使用“\nadmin2”将其添加到下一行。io.readline()
将返回换行符。这意味着如果您只有一个条目,您可能会得到admin
,但如果行数更多,您将得到admin\n
相反,您可以:
tempuser = file.readline().strip()
与问题无关,但您可以大量清理代码。例如,用于读取文件:
def read_file(path):
with open(path, 'r') as f:
return [line.strip() for line in f]
users = read_file('users.secure')
passwords = read_file('passwords.secure')
这些文件看起来像什么?文件的确切内容:adminPost在你的问题中,而不是在评论中。它会停止读取空白行上的文件。如果有空行,它将不会读取整个文件。这是你的意图吗?“\nadmin”会创建一个空行。谢谢,这很有效。对于我的编码,我很抱歉,我是python新手,因为我最近在学校开始学习python,所以我没有被教太多。我会在以后的课程中尝试使用你的建议。@PHDBanana不要为学习而道歉:)我很高兴你这么做了。