gpt4 book ai didi

python - 读取特定输入的文件 python

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

所以我正在编写代码来登录并创建用户名和密码,登录时,我正在读取一个外部文件,其中包含字典形式的所有用户名和密码,例如{“aaaaaaaa”:“aaaaaaA999”}

这是读取它的代码

f3 = open("helloworld.txt","r")
user = input("Enter login name: ")

if user in f3.read():
passw = input("Enter password: ")
print("")

if user in f3.read() and passw in f3.read():
print ("Login successful!\n")


else:
print("")
print("User doesn't exist!\n")
f3.close()

但是,当我尝试阅读它时,它一直说该用户不存在,有什么建议

最佳答案

函数f3.read()正在一次读取整个文件,并将文件指针移动到末尾。任何在不关闭并重新打开文件的情况下读取的后续文件都将返回 None

您需要实际将文件解析为允许您搜索包含内容的数据结构,而不是检查名称或密码是否存在于整个文件中。如果两个用户具有相同的密码会发生什么?如果您只是在整个文件中搜索单个字符串,则无法确保给定用户名的密码正确。

例如,假设您的文件如下所示:

username1,password1
username2,password2
username3,password3

您的解析代码应该打开并读取文件,并检查包含情况,而不是每次都搜索整个文件:

users = {}

with open("helloworld.txt") as f3:
for line in f3:
name, password = line.split(",")
users[name] = password.strip()

user = input("Enter login name: ")

if user in users:
passw = input("Enter password: ")
print()

if passw == users[user]:
print("Login successful!")

else:
print("Bad password")

else:
print("Bad username")

请注意,我将您的文件打开方式更改为使用 context manager (关键字with)。您应该这样做以获得更可靠的资源管理。您还可以通过将字典生成为 dictionary comprehension 来进行进一步的改进。 ,并且可能通过使用异常来处理字典检查而不是 if X in Y:

with open("helloworld.txt") as f3:
pairs = (line.split(",") for line in f3)
users = {name:password.strip() for name, password in pairs}

user = input("Enter login name: ")
passw = input("Enter password: ")

try:
if passw == users[user]:
print("Login successful!")
else:
print("Bad password")
except KeyError:
print("Bad username")

您甚至可以将用户/密码字典的创建压缩为单个理解,但我认为这会显着妨碍可读性,而没有任何好处。

关于python - 读取特定输入的文件 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46796138/

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