Search code examples
pythonnumpyfileexport-to-csv

How to replace existing csv files by exporting new numpy arrays in python


I want to export numpy arrays as csv files but I may have files with the same names in my folder. So, I want to replace old files with new ones. I am using the following method:

arr=np.array([[1., 2.], [2., 1.]])
np.savetxt('arr.csv', arr, delimiter=',')

But this method overwrites rows of the existing arr.csv file in my folder. Is there a way to completely replace the old file? I do appreciate any help in advance.


Solution

  • np.savetxt (numpy=='1.20.3') overwrites the whole file:

    arr = np.random.random((3, 2))
    np.savetxt('arr.csv', arr, delimiter=',')
    
    >>> %cat arr.csv
    2.123431629646361785e-01,6.914800473216878851e-01
    9.544549349895192769e-01,6.749508363116073495e-01
    2.238126343800779239e-01,3.919697864527211806e-01
    
    arr = np.random.random((1, 2))
    np.savetxt('arr.csv', arr, delimiter=',')
    
    >>> %cat arr.csv
    4.355318781801621464e-01,4.574856378543381563e-01