[Numpy-discussion] Writing arrays to files.
John Hunter
jdhunter at ace.bsd.uchicago.edu
Tue Jan 27 10:45:56 EST 2004
>>>>> "Andrea" == Andrea Riciputi <ariciputi at pito.com> writes:
Andrea> Hi, I need a little help here. I need to write some
Andrea> Numeric arrays (coming from some simulations) to ASCII
Andrea> files. I'm sure it's a well known topic and I'd be happy
Andrea> not to have to reinvent the wheel. I've both 1-dim and
Andrea> 2-dim arrays and I'd like to get something like this:
Andrea> - 1-dim array ASCII file:
Andrea> 0.1 0.2 0.3 etc...
If your array is not monstrously large, and you can do it all in
memory, do
fh = file('somefile.dat', 'w')
s = ' '.join([str(val) for val in a])
fh.write(s)
where a is your 1D array
Andrea> - 2-dim array ASCII file:
Andrea> 0.1 0.2 0.3 0.4 0.5 0.6 etc....
Andrea> How can I get them?
Same idea
fh = file('somefile.dat', 'w')
for row in a:
s = ' '.join([str(val) for val in row])
fh.write('%s\n' % s)
where a is your 2D array
The scipy module also has support for reading and writing ASCII files.
Note if you are concerned about efficiency and are willing to use
binary files, use the fromstring and tostring methods.
JDH
More information about the NumPy-Discussion
mailing list