2

I am using savetxt to save numpy array called 'newresult' to a file.

np.savetxt("test.csv", newresult, delimiter=",")

the 'newresult' numpy array is inside a loop, so at each loop the content of newresult changes. I want to add the new content to test.csv file.

But at each loop the

 np.savetxt("test.csv", newresult, delimiter=",")

is overwriting the content of the test.csv, while I want to add to the existing content.

for example,

loop 1:

 newresult=
   [[ 1  2 3 ]
    [ 12  13  14]]

loop 2

newresult=
      [[ 4  6 8 ]
       [ 19  14  15]]

test.csv content is:

  1, 2 ,3
  12,13,14
  4,6,8
  19,14,15
ryh12
  • 357
  • 7
  • 18
  • http://stackoverflow.com/questions/27786868/python3-numpy-appending-to-a-file-using-numpy-savetxt – cel Apr 24 '17 at 05:42

1 Answers1

5

The first point: you can set the first parameter with a file handle that is opened before the loop with a a(append) flag.

The second point: the savetxt opens file in a binary mode, so you have to add a b(binary) flag.

import numpy as np

with open('test.csv','ab') as f:
    for i in range(5):
        newresult = np.random.rand(2, 3)
        np.savetxt(f, newresult, delimiter=",")

If you wanna format the float type data, you can assign a format string to the fmt parameter of the savetxt. For example:

import numpy as np

with open('test.csv','ab') as f:
    for i in range(5):
        newresult = np.random.rand(2, 3)
        np.savetxt(f, newresult, delimiter=",", fmt='%.4f')

enter image description here

Shi XiuFeng
  • 715
  • 5
  • 13