我正在使用Python 3.5为类进行用户名/密码程序,除了本节之外,一切都运行良好。该代码应该打开.txt文件(如果它不存在则创建一个),然后检查您输入的用户名是否已经在文件中。目前,它似乎正在读取一个空白列表(“[]”)并且基本上看不到要检查的内容,因此它接受用户名,尽管如果您在Windows文件浏览器中打开它,它仍然存在于文件中。
以下是用户名功能:
def registerNewUsername():
checker = 0
while(checker == 0):
usernameInput = input("Please enter a username.\n")
usernameInput.strip()
usernameExists = False
try:
f = open("loginInfo.txt", "a+")
userDataEntry = f.readlines()
f.close()
except:
print("Something went wrong!")
listLines = []
for eachLine in listLines:
entry = eachLine.split()
keep = entry[0]
listLines.append(keep)
print(listLines)
if(usernameInput in userDataEntry):
print("This username already exists. Try again.\n")
usernameExists = True
checker = 0
if("@" in usernameInput and ".edu" in usernameInput and usernameExists == False):
print("\nUsername Accepted\n")
checker = 1
else:
print("You need to include @ and .edu in your username. Try again.\n")
checker = 0
return usernameInput
以下是创建用户/密码列表的功能(在用户名和密码被批准后):
def saveData(passwordInput, usernameInput):
userDataEntry = usernameInput + " " + passwordInput + "\n"
fileObject = open('loginInfo.txt', 'a')
fileObject.write(userDataEntry)
fileObject.close()
然而,登录功能肯定会读取列表并可以使用内部数据,所以这个函数中可能缺少某些东西吗?
def loginExisting():
userDataEntry = open('loginInfo.txt', 'r')
listLines = userDataEntry.readlines()
userDataEntry.close()
userDict = {}
for eachLine in listLines:
entry = eachLine.split()
username = entry[0]
password = entry[1]
userDict[username] = password
checker = 0
while(checker == 0):
print("\nYou've registered already? (OwO) Okay then!\n")
usernameInput = input("Please enter your username:")
passwordInput = input("Please enter your password:")
if(usernameInput in userDict):
if(userDict[usernameInput] == passwordInput):
print("\nLogin successful!\nWelcome back,", usernameInput)
checker = 1
else:
print("Password is incorrect. Try again.")
checker = 0
else:
print("Username does not exist. Try again.")
checker = 0
nextStep = int(input("\nWould you like to:\n1.) Exit\n2.) Log out and return to menu\n\n"))
if(nextStep == 1):
print("\nGoodbye!")
if(nextStep == 2):
print("\nReturning to menu...\n")
return nextStep
非常感谢任何帮助!
答案 0 :(得分:0)
这可能是因为在registerNewUsername
函数中,您运行usernameInput.strip()
而未将其分配给任何内容。如果不将结果返回给变量或其他变量,则不会发生任何事情。尝试再次运行它,将usernameInput.strip()
行更改为usernameInput = usernameInput.strip()
。