Reputation: 17
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': '[email protected]', 'password': 'test123'},
{'username': '[email protected]', 'password': 'test1234'},
{'username': '[email protected]', 'password': 'test123'},
]
The file looks like this:
[email protected],test123
[email protected],test1234
[email protected],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?
Upvotes: 1
Views: 348
Reputation: 123393
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.
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': '[email protected]', 'password': 'test123'},
{'username': '[email protected]', 'password': 'test1234'},
{'username': '[email protected]', 'password': 'test123'}]
Upvotes: 0
Reputation: 24133
Use DictReader
in the csv
module:
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 = """[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')])]
Upvotes: 0
Reputation: 754
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.
Upvotes: 0
Reputation: 1301
You want a list of dictionaries, but you only create a dictionary that it's modified each time in for loop. 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)
Upvotes: 2