2017-09-05 102 views
2

最有效的方法下面的代码主要执行以下操作:到文本文件的内容转换成字典在python

  1. 注意到文件的内容,并读入两个列表(剥离和拆分)
  2. 拉链两一起列入字典
  3. 使用字典创建“登录”功能。

我的问题是:是否有更简单更高效(快速)创建从文件内容的字典的方法:

文件:

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 /咸菜,包括所有对于初学者的必要信息访问

在此先感谢

+1

从未保持密码明文,你应该使用某种散列函数,例如https://passlib.readthedocs.io/ –

回答

8

只需通过csv module

import csv 

with open("userinfo.txt") as file: 
    list_id = csv.reader(file) 
    userinfo_dict = {key:passw for key, passw in list_id} 

print(userinfo_dict) 
>>>{'user1': 'pass1', 'user2': 'pass2'} 

with open()是同一类型的上下文管理器的使用打开文件,并处理关闭。

csv.reader是加载文件的方法,它会返回一个可以直接迭代的对象,就像在理解列表中一样。但不是使用理解词汇表,而是使用理解词典。

建设有一个修真风格的字典,你可以使用这个语法:

new_dict = {key:value for key, value in list_values} 
# where list_values is a sequence of couple of values, like tuples: 
# [(a,b), (a1, b1), (a2,b2)] 
+0

能否请你解释一下,对于初学者和教学目的来说,关键是:passw关键部分。我可以使用任何变量吗? Misscomputing感谢您的反馈,请记住@ endo.anaconda的评论,下一步是用一些散列替换密码 – MissComputing

+0

此外,美丽 - 谢谢! – PRMoureu

2

如果你不想使用csv模块,您可以简单地这样做:

userinfo_dict = dict() # prepare dictionary 
with open("userinfo.txt","r") as f: 
    for line in f: # for each line in your file 
     (key, val) = line.strip().split(',') 
     userinfo_dict[key] = val 
# now userinfo_dict is ready to be used 
+0

另外,您还可以发表评论以说明它究竟在做什么(不是我的意思) – MissComputing