是否可以在使用 open( "file" , "a+" ) 时获得与 user_file.readlines()].index(login_username) 中的行相同的结果



我正在尝试用python进行简单的登录和注册系统(我是python的新手,这对我自己来说是一个小项目(。为了让注册系统工作,我必须附加到一个文本文件中,这样我就可以添加额外的注册信息,但同时我也需要让登录工作。通过使用

[line.rstrip('n') for line in user_file.readlines()].index(login_username)我试图获得用户的用户名输入,然后找到用户名所在的行(在txt文件中(,根据它所在的行,它将检查另一个包含密码的文本文件,并查看中的该行是否有密码。

重复:有没有办法在使用open("username", "a+)时也得到与[line.rstrip('n') for line in user_file.readlines()].index(login_username)相同的结果

这是我的代码


login_password = None
login_username = None
log_right = False
signup_password = None
signup_username = None
# makes sure that password is correct
cl_pw = False
# makes sure when they sign up the username.txt isn't taken
taken_username = False
pw_file = open("passwor and username", "a+")
user_file = open("username.txt", "a+")
while log_right == False:

log_sign = input("Do you want to Log In or Sign Up: ")
if log_sign == "log in" or log_sign == "Log in" or log_sign == "Log In" or log_sign == "log In":
print("loading...")
time.sleep(0.4)
while cl_pw == False:
login_username = input("Username: ")
login_password = input("Password: ")
if login_username in open("username.txt").read():
lines = int([line.rstrip('n') for line in user_file.readlines()].index(login_username))
#i think there is something wrong beyond this line
if pw_file.readlines()[lines] == login_password:
print("you have logged in")
else:
print("You have entered the wrong password")
print(lines)
cl_pw = True
log_right = True
elif login_username == "":
print("you are not registered. Do you want to sign up?")
else:
print("you are not registered. Do you want to sign up?")

elif log_sign == "Sign Up" or log_sign == "sign up" or log_sign == "Sign up" or log_sign == "sign Up":
time.sleep(0.6)
print("loading...")
time.sleep(0.4)
while taken_username == False:
signup_username = input("Username: ")
signup_password = input("Password: ")
if signup_username in open("username.txt").read():
print("The username.txt you chose have been take, please pick another username.txt")
else:
user_file.write("n" + signup_username)
pw_file.write("n" + signup_password)
print("Sign up SUCCESS")
taken_username = True
log_right = True
else:
print("Please enter either Log In or Sign Up")
pw_file.close()
user_file.close()

如果还有任何问题需要回答,以便获得更多信息,请随时询问,我会尽力回答。谢谢

您可以直接迭代文件并使用enumerate来获取行号。这不会一次消耗整个文件,而是在第一次匹配时停止(这也会在内存中保存一个临时列表(:

next(i for i, line in enumerate(user_file) if line.rstrip('n') == login_username)

在行之间读取时,用户的密码在密码文件中与在用户文件中的行位于同一行。您可以使用zip对每个文件中的行进行串联迭代,这将减轻您从一个文件中查找索引并在另一个文件使用索引的负担。这是一个玩具的例子。

login_username = 'myname'
login_password = 'mypwd'
canlogin = False
with open("passwor and username") as pw_file, open("username.txt") as user_file:
for name,pwd in zip(user_file,pw_file):
if login_username == name.strip() and login_password == pwd.strip():
canlogin = True
break
if canlogin:
print('login succesfull')
else:
print('either uname or pwd are wrong')

最新更新