reading data columns into separate lists

V

Viswa

PythonGurus,

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.

Thanks in advance,
viswa.
 
P

Peter Otten

Viswa said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top