alice alice - 1 year ago 106
Python Question

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
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
. Is there a way to do this with

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

Answer Source

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):

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


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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download