By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,235 Members | 1,022 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,235 IT Pros & Developers. It's quick & easy.

reading data columns into separate lists

P: n/a
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.
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.