alice
alice

Reputation: 274

Python: Keep savefig from overwriting old plots

I simply use

plt.savefig(filename+'.png', format='png')

to save my plots. But I want to keep my old versions of filename.png when I create a new one (using different colour codes, etc.) without always having to come up with a new filename.

Since I don't do that in one run, this doesn't help me. I found this on how to keep Python from overwriting files, but that's for os. Is there a way to do this with savefig?

In the end I want Python to check whether filename.png exists and only if so, save the new figure as filename1.png, filename2.png, etc.

Upvotes: 5

Views: 10276

Answers (1)

user707650
user707650

Reputation:

You'll have to provide some unique name yourself: matplotlib won't do it for you. Nor will matplotlib check for existence of your current filename. I would write a loop along the following lines:

(untested code)

import os
i = 0
while True:
    i += 1
    newname = '{}{:d}.png'.format(filename, i)
    if os.path.exists(newname):
        continue
    plt.savefig(newname)
    break

Note: if the extension is already .png, you don't need to set the format to png explicitly.

Edit

I realized the above is too long-winded, and only came about because I wanted to avoid doing the string formatting twice. The following is probably more logical:

import os
i = 0
while os.path.exists('{}{:d}.png'.format(filename, i)):
    i += 1
plt.savefig('{}{:d}.png'.format(filename, i))

Upvotes: 6

Related Questions