reading data columns into separate lists
Peter Otten
__peter__ at web.de
Sun May 2 05:03:59 EDT 2004
Viswa wrote:
> I would like to read the ascii data from a file with many columns
> into a list. I want the type to be float.
>
> data=open('dat1.dat','r')
>
> lines=data.readlines()
> print lines
>
> Here, the data x1,x2,x3,x4 are separated
> by tabs and end with new line.
> 1\t2\t3\t4\n
> ...
> ...
>
> Is there a way to read the delimiter separated data
> straightaway to a list of fixed type.
from random import random
# generate sample data (10 lines, 5 columns)
f = file("tmp.txt", "w")
for n in range(10):
f.write("\t".join([str(random()) for n in range(5)]))
f.write("\n")
f.close()
# read it into a list of lists
rows = [map(float, line.split()) for line in file("tmp.txt")]
print len(rows), "rows read"
print "contenst of 4th row:"
print rows[3]
For more heterogeneous data you may have a look at the csv module (new in
Python 2.3).
Peter
More information about the Python-list
mailing list