'Preventing overwriting when using numpy.savetxt

Is there built error handling for prevent overwriting a file when using numpy.savetxt? If 'my_file' already exists, and I run

numpy.savetxt("my_file", my_array)

I want an error to be generated telling me the file already exists, or asking if the user is sure they want to write to the file.



Solution 1:[1]

You can pass instead of a filename a file handle to np.savetxt(), e.g.,

import numpy as np

a = np.random.rand(10)
with open("/tmp/tst.txt", 'w') as f:
    np.savetxt(f,a)

So you could write a helper for opening the file.

Solution 2:[2]

Not in Numpy. I suggest writing to a namedTemporaryFile and checking if the destination file exists. If not, rename the file to a concrete file on the system. Else, raise an error.

Solution 3:[3]

Not an error handler, but it's possible to create a new version in the form of:

file  
filev2  
filev2v3  
filev2v3v4 

so that no file ever gets overwritten.

n=2
while os.path.exists(f'{file}.txt'):
    file = file + f'v{n}' 
    n+=1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dietrich
Solution 2
Solution 3 BSMP