Reputation: 113
I am attempting to take information from a text file and turn it into a list of lists that I later do more with. The text file is formatted so that each piece of information is separated by ", " and then at the end of each "person" there is a "\n" For example, 111, Joe, Jones, 09-01-1980, 10-19-1999, 95000
I am close. But stuck on one small thing. My current code:
def readFile(fileName):
myFileObj = open(fileName, "r")
peopleStr = myFileObj.read()
peopleList = peopleStr.split("\n")
newPeopleList = []
for el in peopleList:
sub = el.split(" ,")
newPeopleList.append(sub)
print(newPeopleList)
return newPeopleList
This newPeopleList returns
[['111, Joe, Jones, 09-01-1980, 10-19-1999, 95000'], ['113, James, Jo, 10-02-1982, 10-18-1998, 85000'], ['123, Jordan, Joul, 08-04-1988, 10-17-1988, 80000']]
But what I need is
[[111, 'Joe', 'Jones', '09-01-1980', '10-19-1999', 95000], [113, 'James', 'Jo', '10-02-1982', '10-18-1998', 85000], [123, 'Jordan', 'Joul', '08-04-1988', '10-17-1988', 80000]]
So they each can be their own item in the list!
I hope this makes some sense, and I appreciate any help!
Upvotes: 4
Views: 79
Reputation: 825
you can get what you want more pythonic:
list(map(lambda x:x.split(', '),open(filename,'r').readlines()))
you delimiter which is ' ,' in your own code is wrong, while it needs ', '.
Upvotes: 0
Reputation: 6080
listOfLists = []
with open(filename, "r") as msg:
for line in msg:
listOfLists.append(line.strip().replace(" ","").split(","))
msg.close()
This should make it. You read your file line by line, you replace the blank spaces by nothing, you split by "," each line to make a list of it that you store in your list of lists.
Upvotes: 2
Reputation: 15470
Try this:
newlist = [[y.split(", ")] for x in newPeopleList for y in x]
print(newlist)
Upvotes: 0