Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the file with different name and not overwriting existing one

Tags:

python

file

plot

I need to run a python script repeatedly over different data set. This python script test.py processes the data set, plot and save the result using the command.

plt.savefig('result.png')

How can I ensure that when the same test.py scripts runs on another data set.. the new result.png doesn't overwrite my previous result? Basically before executing plt.savefig('result.png'), I need to check if result.png already exist and if does then rename the result to any other name like

result1.png
result2.png

Otherwise, in the next post processing the file is overwritten.

like image 279
HaWa Avatar asked Nov 13 '15 10:11

HaWa


People also ask

How do you save an open file under a different file name?

Click the File tab. Click Save As. In the File name box, enter a new name for the file. Click Save.

What mode overwrite existing text in a file?

To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.


2 Answers

You can use os.path.exists to check whether the file already exists, and if so, append a number. Repeat with the new file name until you find one that does not yet exist.

def unique_file(basename, ext):
    actualname = "%s.%s" % (basename, ext)
    c = itertools.count()
    while os.path.exists(actualname):
        actualname = "%s (%d).%s" % (basename, next(c), ext)
    return actualname

Example-usage:

for i in range(5):
    with open(unique_file("foo", "txt"), "w") as f:
        f.write(str(i))
like image 179
tobias_k Avatar answered Oct 28 '22 04:10

tobias_k


import time
if os.path.exists('result.png'):
    plt.savefig('result_{}.png'.format(int(time.time())))
else:
    plt.savefig('result.png')
like image 28
Mangu Singh Rajpurohit Avatar answered Oct 28 '22 05:10

Mangu Singh Rajpurohit