最有效的方法下面的代码主要执行以下操作:到文本文件的内容转换成字典在python
- 注意到文件的内容,并读入两个列表(剥离和拆分)
- 拉链两一起列入字典
- 使用字典创建“登录”功能。
我的问题是:是否有更简单更高效(快速)创建从文件内容的字典的方法:
文件:
user1,pass1
user2,pass2
代码
def login():
print("====Login====")
usernames = []
passwords = []
with open("userinfo.txt", "r") as f:
for line in f:
fields = line.strip().split(",")
usernames.append(fields[0]) # read all the usernames into list usernames
passwords.append(fields[1]) # read all the passwords into passwords list
# Use a zip command to zip together the usernames and passwords to create a dict
userinfo = zip(usernames, passwords) # this is a variable that contains the dictionary in the 2-tuple list form
userinfo_dict = dict(userinfo)
print(userinfo_dict)
username = input("Enter username:")
password = input("Enter password:")
if username in userinfo_dict.keys() and userinfo_dict[username] == password:
loggedin()
else:
print("Access Denied")
main()
对于你的答案,请求E:
a)使用现有功能和代码,以适应 b)中提供的解释/评论(特别是对于使用分流/条) c)当使用JSON /咸菜,包括所有对于初学者的必要信息访问
在此先感谢
从未保持密码明文,你应该使用某种散列函数,例如https://passlib.readthedocs.io/ –