gpt4 book ai didi

python - 与用户输入相比,用户登录从文件读取失败

转载 作者:行者123 更新时间:2023-12-01 03:43:43 24 4
gpt4 key购买 nike

我正在编写一个程序来验证用户名:

def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'r') as f:
if f.readline() is "":
username = raw_input("First login, enter a username to use: ")
with open('username.txt', 'a+') as user:
user.write(username)
else:
login_id = raw_input("Enter username: ")
if login_id == str(f.readline()):
return True
else:
print "Invalid username."
return False


if __name__ == '__main__':
if user_login() is not True:
print "Failed to verify"

每次我运行它时,它都会输出以下内容:

Enter username: tperkins91
Invalid username.
Failed to verify

如何比较用户输入和从文件中读取的内容?

最佳答案

在另一个嵌套上下文中再次打开同一文件不是一个好主意。相反,在追加模式下打开一次文件,并在需要时使用f.seek(0)返回到开头:

def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'a+') as f:
if f.readline() is "":
username = raw_input("First login, enter a username to use: ")
f.seek(0)
f.write(username)
# return True/False --> make the function return a bool in this branch
else:
login_id = raw_input("Enter username: ")
f.seek(0)
if login_id == f.readline():
return True
else:
print "Invalid username."
return False


if __name__ == '__main__':
if user_login() is not True:
print "Failed to verify"

您可能需要考虑在 if 分支中返回 bool 值,以便函数的返回类型与 bool 一致,而不是像中那样的 None目前的情况。

关于python - 与用户输入相比,用户登录从文件读取失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com