Reputation: 21
Using this code I can separate data on a line and put it into a list as well as separating each line and making separate lists out of them.
p=open('file.txt').readlines()
for line in p:
line = line.strip('\n')
s = line.split()
print(s)
When I run this code I get this:
['Danielle', 'Jennings', '5', '6', '5']
['Fred', 'Armstrong', '0', '0', '2']
I want to create a variable for each of these lists e.g. value1= ['Danielle', 'Jennings', '5', '6', '5', '5.3', '6'] but I'm not sure how. I then want to use the 'zip' function to join each corresponding value in this list. Does anyone have any idea how to do this?
UPDATE: I have turned all of the file lines into one list. But, if I didn't want to add every part of the line to the list, how would I do this? For example, I only want to add one of the numbers to the list and then sort it but I just get this. ['9', '1', '4', 'Daniel', 'Ant', 'Kent', 'Riser', 'Abby', 'James'] When instead I want something more like this: ['Daniel', 'Riser', '1'] ['Ant', 'James', 9] etc
Upvotes: 1
Views: 116
Reputation: 24133
with open('file.txt') as text:
people = [line.strip().split() for line text]
Upvotes: 0
Reputation: 238051
The best way probably would be to put them into a dict
p=open('file.txt').readlines()
value_dict = {}
for i,line in enumerate(p):
line = line.strip('\n')
s = line.split()
value_dict["value{:02d}".format(i)] = s
print(s)
It would also be possible to create local variables as you go, but I would advise against it. I think better to have everything in one place, in this case a dict.
Upvotes: 1