Skip to content
Advertisement

How do I check the existing file with same name in the directory and use python to rename new files to save?

I am using plt.savefig to save a plot generated by matplotlib.pyplot, and I want to save my figure with different names each time I run the code. How can I do that?

Advertisement

Answer

The easiest would probably be to use the current time, if you don’t save multiple files per second.

import datetime

ts = datetime.datetime.now().strftime("%Y%m%d-%H.%M.%S")
plt.savefig(f"figure-{ts}.png")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement