Reputation: 31
So im wanting to read from a file and put each line of it into a list.
Say I have a file named MyFile.txt or MyFile.csv containing the following three lines of numbers/decimals:
49.55,2,77.09,18,1,2.34,32.11
33,11.22,33.21,56,76.55
8,9,44.7,90.99,12.21,1.01
I want the program to open the file then read line one and put it into a list ~ say L1list. I then want it to make L2list & L3list for lines 2 & 3. Once that's done I want to be able to work out the total for a list, average, max & min etc. I'm pretty confident with this part using sum (), len(),max(), min() etc.
Its the populating of the lists that has me stuck. Im getting the wrong totals, lengths etc. Thought maybe its the full-stops or comers. but i need the decimal places and thought lists need the comers to separate.
So far i have tried:
filename = 'MyFile.txt'
fin=open(filename,'r')
L1list = fin.readline()
L2list = fin.readline()
L3list = fin.readline()
Also:
L1list.append(fin.readline())
Along with:
L1list = [i.strip().split() for i in fin.readlines()]
A little stuck as to whats going wrong.
Upvotes: 3
Views: 1706
Reputation: 29103
So what goes wrong with your code? Have your tried something like this:
L1list = [map(float, i.strip().split(',')) for i in fin.readlines()]
Or with data check:
with open(filename,'r') as fin:
values = [map(float, [x for x in line.strip().split(',') if x]) for line in fin]
Also you can take a look at the csv module
Upvotes: 5
Reputation: 1172
>>> '49.55,2,77.09,18,1,2.34,32.11'.split(',')
['49.55', '2', '77.09', '18', '1', '2.34', '32.11']
Please try to print
and see what's going on.
And you may want to use http://docs.python.org/2/library/csv.html for more complex CSV file.
Upvotes: 1
Reputation: 421
I believe you need something like:
L1list = map(float, fin.readline().strip().split(","))
Upvotes: 1