简体   繁体   English

如何从给定的txt文件创建字典?

[英]How do I create a dictionary from given txt file?

I have a text file consisting of usernames and a passwords, separated by a comma that I need to convert into a dictionary like this: 我有一个由用户名和密码组成的文本文件,用逗号分隔,我需要将其转换成这样的字典:

userData = [{'username': 'something@test.com', 'password': 'test123'},
            {'username': 'somethingelse@test.com', 'password': 'test1234'},
            {'username': 'somethingmore@test.com', 'password': 'test123'},
            ]

The file looks like this: 该文件如下所示:

something@test.com,test123
somethingelse@test.com,test1234
somethingmore@test.com,test123

I tried the following, but it only returns the last line of the text file, so I assume the dictionary is overwritten for each line. 我尝试了以下操作,但是它仅返回文本文件的最后一行,因此我假设字典被每一行覆盖。

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

What can I do to get the correct output? 我该怎么做才能获得正确的输出?

You want a list of dictionaries, but you only create a dictionary that it's modified each time in for loop. 您需要一个字典列表,但是您只创建一个字典,每次在for循环中都会对其进行修改。 You have to create another dictionary for each line and store it in list. 您必须为每行创建另一个字典并将其存储在列表中。
Try this: 尝试这个:

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)

This should work: 这应该工作:

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

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

In your original code you're not actually altering the dictionary, just one username and password. 在您的原始代码中,您实际上并没有更改字典,只需更改一个用户名和密码即可。

EDIT: I misread the question. 编辑:我误读了问题。 Mine stores each username as a key and each password as the value. 我的存储每个用户名作为密钥,每个密码作为值。

Use DictReader in the csv module: csv模块中使用DictReader

import csv

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

For example: 例如:

>>> 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')])]

It looks like what you actually want to do is create a list of dictionary objects. 看起来您实际上想要做的是创建字典对象列表。 I'd use the csv module to read the data, since the content of the file appears to be that of Character Separated Values. 我将使用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)

Output: 输出:

[{'username': 'something@test.com', 'password': 'test123'}, {'username': 'somethingelse@test.com', 'password': 'test1234'}, {'username': 'somethingmore@test.com', 'password': 'test123'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM