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

Gabriel Genellina gagsl-py at yahoo.com.ar
Sun Feb 11 21:35:23 EST 2007


En Sun, 11 Feb 2007 22:47:30 -0300, mech point <srikanth.allu at gmail.com>  
escribió:

> 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]))

-- 
Gabriel Genellina




More information about the Python-list mailing list