2017-09-05 100 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