【发布时间】:2018-02-14 04:55:32
【问题描述】:
下面的代码基本上做了以下事情:
- 获取文件内容并将其读入两个列表(剥离和拆分)
- 将两个列表一起压缩到字典中
- 使用字典创建“登录”功能。
我的问题是:有没有更简单更有效(更快)的方法从文件内容创建字典:
文件:
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()
如需解答,请:
a) 使用已有的函数和代码进行适配 b) 提供解释/cmets(特别是对于split/strip的使用) c) 如果使用 json/pickle,请包括初学者访问的所有必要信息
提前致谢
【问题讨论】:
-
永远不要以明文形式保存密码,您应该使用某种散列函数,例如passlib.readthedocs.io
标签: python file dictionary