2017-01-25 9 views
1

私はこのような辞書に変換する必要がカンマで区切られたユーザ名とパスワードからなるテキストファイル、持っている:特定のtxtファイルから辞書を作成するにはどうすればよいですか?

userData = [{'username': '[email protected]', 'password': 'test123'}, 
      {'username': '[email protected]', 'password': 'test1234'}, 
      {'username': '[email protected]', 'password': 'test123'}, 
      ] 

ファイルは次のようになります。

[email protected],test123 
[email protected],test1234 
[email protected],test123 

を私は次のようにしようとしましたが、テキストファイルの最後の行だけを返すので、各行に辞書が上書きされていると仮定します。

file = open('username.txt', 'r') 
userData = {} 
userData['username'] = '' 
userData['password'] = '' 

for line in file: 
    x = line.split(',') 
    un = x[0] 
    pw = x[1] 
    userData['username']=un 
    userData['password']=pw 

正しい出力を得るにはどうすればよいですか?

+1

はい、それは上書きされます。あなたが望む出力は、辞書のリストです - リストはどこですか?ループの中に辞書を作成してみませんか? – jonrsharpe

+3

私は平文で重要なもののためにパスワードを保存していないことを期待しています。 – byxor

+2

問題は辞書*のリストが必要なことです。 'userData'は**辞書ではありません** ... –

答えて

2

辞書のリストが必要ですが、ループのたびに変更された辞書のみを作成します。各行に別の辞書を作成し、それをリストに格納する必要があります。
はこれを試してみてください:

file = open('username.txt', 'r') 
userDataList = [] 

for line in file: 
    x = line.split(',') 
    userData = {} 
    userData['username'] = x[0] 
    userData['password'] = x[1] 
    userDataList.append(userData) 
0

これは動作するはずです:

file = open('username.txt', 'r') 
userData = {} 

for line in file: 
    x = line.split(',') 
    userData[x[0]] = x[1] 

をあなたの元のコードでは、あなたが実際に辞書を変更していない、ただ1つのユーザ名とパスワードを。

EDIT:質問を誤解しました。 Mineは各ユーザ名をキーとして保存し、各パスワードは値として保存します。 csvモジュールで

0

使用DictReader:たとえば

import csv 

with open('usernames.txt') as csvfile: 
    reader = csv.DictReader(csvfile, 
          fieldnames=['username', 'password']) 
    users = list(reader) 

>>> import csv 
>>> import pprint 
>>> from StringIO import StringIO 

>>> content = """[email protected],test123 
... [email protected],test1234 
... [email protected],test123""" 

>>> usernames = StringIO(content) 
>>> pprint(list(csv.DictReader(usernames, 
...       fieldnames=['username', 'password']))) 
[OrderedDict([('username', '[email protected]'), ('password', 'test123')]), 
OrderedDict([('username', '[email protected]'), 
       ('password', 'test1234')]), 
OrderedDict([('username', '[email protected]'), ('password', 'test123')])] 
0

それはあなたが実際に何をしたいかのように見えますが、辞書オブジェクトのリストを作成することです。私はcsvモジュールを使用して、ファイルの内容が文字区切り文字の内容であるように見えるため、データを読むことができます。

import csv 
import sys 

def open_csv(filename, mode='r'): 
    """Open a csv file in proper mode depending on Python verion.""" 
    return(open(filename, mode=mode+'b') if sys.version_info[0] == 2 else 
      open(filename, mode=mode, newline='')) 

def read_data(filename, fieldnames): 
    with open_csv(filename, mode='r') as file: 
     for row in csv.DictReader(file, fieldnames=fieldnames): 
      yield row 

fieldnames = 'username password'.split() 
user_data = [row for row in read_data('username.txt', fieldnames)] 

print(user_data) 

出力:

[{'username': '[email protected]', 'password': 'test123'}, {'username': '[email protected]', 'password': 'test1234'}, {'username': '[email protected]', 'password': 'test123'}]

関連する問題