3

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.

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanx and sorry @Aniket- was a bit disappointed by removing the text from my post
I was kidding with the -ve vote. I thought its the most elegant solution for this problem, you put in comments and was going to ask you to post it as an answer.
1

I believe you need something like:

L1list = map(float, fin.readline().strip().split(","))

Comments

1
>>> '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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.