[Numpy-discussion] Appending a numpy array to binary file

Scott Sinclair scott.sinclair.za at gmail.com
Wed Mar 23 08:23:16 EDT 2011


On 22 March 2011 17:22, Robert Kern <robert.kern at gmail.com> wrote:
> On Tue, Mar 22, 2011 at 05:37, Alessandro
> <alessandro.sanginario at polito.it> wrote:
>> Hi everybody,
>>
>> I'm trying to append, inside a loop, into a binary file some arrays using
>>
>> numpy.save(file, arr) but wvhen I open it there is only the last array I
>> saved.
>>
>> If I use savetxt it works perfectly. Do you know how can I append data to a
>> binary file inside a loop?
>>
>> Example:
>>
>> x = arange(10)
>>
>> fp = open("TempFile","ab")
>>
>> for i in range(3):
>>
>> save(fp,x)
>>
>> fp.close()
>>
>> Data saved into the file is: [0,1,2,3,4,5,6,7,8,9] but I would like:
>> [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9 0,1,2,3,4,5,6,7,8,9]
>
> The data is actually saved three times...

> You can read all
> three arrays by doing repeated np.load() calls on the same file
> object:
>
> fp = open('TempFile', 'rb')
> for i in range(3):
>    print np.load(fp)

You can also use numpy.savez if you want to save several arrays and
read them back with a single call to numpy.load.

Cheers,
Scott



More information about the NumPy-Discussion mailing list