November 5th, 2012, 11:00 PM
Python Read file. Make a List per line
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:
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'
L1list = fin.readline()
L2list = fin.readline()
L3list = fin.readline()
A little stuck as to whats going wrong.
L1list = [i.strip().split() for i in fin.readlines()]
Thanks in advance. Oh and im using Python 2.7.3
November 6th, 2012, 04:20 AM
Something like this?
>>> with open('MyFile.txt') as f:
... L = [list(map(float, line.strip().split(','))) for line in f]
[[49.55, 2.0, 77.09, 18.0, 1.0, 2.34, 32.11], [33.0, 11.22, 33.21, 56.0, 76.55], [8.0, 9.0, 44.7, 90.99, 12.21, 1.01]]
>>> (L1list, L2list, L3list) = L
[49.55, 2.0, 77.09, 18.0, 1.0, 2.34, 32.11]
[33.0, 11.22, 33.21, 56.0, 76.55]
[8.0, 9.0, 44.7, 90.99, 12.21, 1.01]
November 6th, 2012, 01:13 PM
you could store them in an array
an display a specified line with ARRAY[i]
FILE = open("file.txt","rt")
ARRAY = 
for line in FILE:
November 7th, 2012, 05:21 AM
Why you map() at all when you can use list comprehensions all the way?
Originally Posted by Lux Perpetua
L = [[float(num) for num in line.strip().split(',')] for line in f]
My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)