我正在尝试建立一个基本的注册和登录系统。我希望将用户名和密码保存到文本文件中。当用户在登录部分输入信息时,我要编程以读取文本文件以查看信息是否正确。如果不是,则提示再次尝试。到目前为止,当文本文件中存在用户名并且我输入正确时,程序将返回“此用户名不存在,请重试”。
这使用的是Python 3,我尝试查看其他线程,但它们似乎无法回答我的问题。我已将读写模式从w +更改为a +,但这似乎无济于事。我也尝试过手动将信息输入文本文件,但这似乎也不起作用。
from time import sleep
import linecache
print("Welcome to the banking system.")
sleep(1)
def home():
print("Please select to login or create a new account.")
print("1.Register\n2.Login")
login_choice = input()
if login_choice == "1":
register()
elif login_choice == "2":
login()
else:
home()
def register():
f = open("userpassword.txt", "a+")
print("Please make a memorable username")
username = input()
f.write(username + "\n")
sleep(0.5)
print("Please make a memorable password")
password = input()
f.write(password)
f.close()
home()
def login():
print("Please enter your username.")
ask_username = input()
try:
f = open("userpassword.txt", "a+")
global filename
filename = "userpassword.txt"
user_line = 0
username = linecache.getline(filename, user_line)
if ask_username != username:
print("This username doesn't exist, please try again.")
sleep(0.2)
f.close()
login()
else:
pass_line = 1
password = linecache.getline(filename, pass_line)
print("Please enter your password.")
ask_password = input()
if ask_password != password:
f.close()
login()
else:
print("Welcome " + username)
f.close()
except NameError:
sleep(0.2)
print("Please register before logging in.")
register()
home()
没有任何错误消息,但是它返回了错误的输出。