Reputation: 60
I have a file with a list of names that are organized as last name , first name. I want to achieve creating another file but organizing it as first name , last name.
Using these hints: Iterate over each line, and
Split the names into firstname and lastname
Store that into a dictionary
Append the dictionary into a list
After following the above statements you will have a list of names as shown
[ {‘fname’: ‘Jeanna’ , ‘lname’: ‘Mazzella’}, {‘fname’: ‘Liane’ , ‘lname’: ‘Spataro’}, …….. ]
source.txt =
Mazzella, Jeanna
Spataro, Liane
Beitz, Sacha
Speegle, Pura
Allshouse, Parker
What I have so far in an attempt to split the names into first names and last names. I'm stuck in the part of having the output as the hint given. Can someone help?
f = open('source.txt')
namlist = f.read()
split = namlist.split()
fname = split[1:5:2] #This gets the first names
print(fname)
for i in fname:
print(i)
lname = split[0:5:2] #This gets the last names
for j in lname:
print(j)
Upvotes: 3
Views: 80
Reputation: 26039
You can easily do in one pass without using additional data structures (disclaimer: untested):
with open('source.txt') as fin, open('destination.txt', 'w') as fout:
for line in fin:
lastname, firstname = line.strip().split(', ')
fout.write(f'{firstname}, {lastname}\n')
Upvotes: 2
Reputation: 106881
If your goal is to simply swap the first names and the last names in the source file, you can use the str.partition
method to partition the lines with ', '
, reverse the resulting lists and join them back to strings:
with open('source.txt') as f, open('updated.txt', 'w') as output:
output.write('\n'.join(''.join(line.rstrip().partition(', ')[::-1]) for line in f) + '\n')
Upvotes: 0
Reputation: 106881
You can use a list comprehension with a dict constructor that takes a zipped keys and values from lines in the file splitted by ', '
:
[dict(zip(('lname', 'fname'), line.rstrip().split(', '))) for line in f]
Given your sample input, this returns:
[{'lname': 'Mazzella', 'fname': 'Jeanna'}, {'lname': 'Spataro', 'fname': 'Liane'}, {'lname': 'Beitz', 'fname': 'Sacha'}, {'lname': 'Speegle', 'fname': 'Pura'}, {'lname': 'Allshouse', 'fname': 'Parker'}]
Upvotes: 1