我有一个由用户名和密码组成的文本文件,用逗号分隔,我需要将其转换为这样的字典:
userData = [{'username': 'something@test.com', 'password': 'test123'},
{'username': 'somethingelse@test.com', 'password': 'test1234'},
{'username': 'somethingmore@test.com', 'password': 'test123'},
]
该文件如下所示:
something@test.com,test123
somethingelse@test.com,test1234
somethingmore@test.com,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
我该怎么做才能获得正确的输出?
答案 0 :(得分:2)
您需要一个词典列表,但您只需创建一个每次进行for循环时都要修改的词典。您必须为每一行创建另一个字典并将其存储在列表中 试试这个:
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)
答案 1 :(得分:0)
这应该有效:
file = open('username.txt', 'r')
userData = {}
for line in file:
x = line.split(',')
userData[x[0]] = x[1]
在原始代码中,您实际上并没有改变字典,只是一个用户名和密码。
编辑:我误解了这个问题。我将每个用户名存储为密钥,将每个密码存储为值。答案 2 :(得分:0)
在DictReader
模块中使用csv
:
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 = """something@test.com,test123
... somethingelse@test.com,test1234
... somethingmore@test.com,test123"""
>>> usernames = StringIO(content)
>>> pprint(list(csv.DictReader(usernames,
... fieldnames=['username', 'password'])))
[OrderedDict([('username', 'something@test.com'), ('password', 'test123')]),
OrderedDict([('username', 'somethingelse@test.com'),
('password', 'test1234')]),
OrderedDict([('username', 'somethingmore@test.com'), ('password', 'test123')])]
答案 3 :(得分: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': 'something@test.com', 'password': 'test123'},
{'username': 'somethingelse@test.com', 'password': 'test1234'},
{'username': 'somethingmore@test.com', 'password': 'test123'}]