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: Debian GNU/Linux 8 (desktop, home laptop, work laptop), Raspbian GNU/Linux 8 (nameserver), Ubuntu 14.04.3 LTS (HTPC), PC-BSD 10.2 (testbed), Android 4.2.1 (tablet)