Read/write 2D data from/to file..?

M

mech point

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

Thank you,
srikanth
 
J

John Machin

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

Presuming that it is either mandatory to adopt the same style (or lack
thereof) as the input code, and/or futile to suggest otherwise:

file('data2','w').write('\n'.join(' '.join(repr(item)for item in
row)for row in rows)+'\n')
 
G

Grant Edwards

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

for r in rows:
file.write(" ".join(map(str,r)) + "\n")
 
G

Gabriel Genellina

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

This way uses the same structures as your example; line.split(",") ->
",".join(...); map(float,...) -> map(str,...)

yourfile.writelines(",".join(map(str,row))+"\n" for row in rows)

If you are using Python<2.5, put [] inside the writelines call:
writelines([","...]).
Or move the iteration outer. If you want control on the format too:
for row in rows:
yourfile.write("%.2f,%.6g\n" % (row[0], row[1]))
 
G

Grant Edwards

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

for r in rows:
file.write(" ".join(map(str,r)) + "\n")

Doh. Bad choice of names for my file object:

f = file("data","w")
for r in rows:
f.write(" ".join(map(str,r)) + "\n")

You can do it on one line if you want, but I find the above a
little bit clearer.
 
V

Vasily Sulatskov

I was able to read the data from file into a two dimensional array
(lists)

rows=[map(float,line.split())for line in file("data")]

but How to write them back into the file.

Using matplotlib it will be:

import pylab
rows = pylab.load('src.dat')
pylab.save(rows, 'dst.dat')
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top