如何查看目录中已有的同名文件并使用python重命名新文件保存?

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

我正在使用 plt.savefig 来保存由 matplotlib.pyplot 生成的图,并且每次 运行 代码时我都想用不同的名称保存我的图形。我该怎么做?

如果您不每秒保存多个文件,最简单的方法可能是使用当前时间。

import datetime

ts = datetime.datetime.now().strftime("%Y%m%d-%H.%M.%S")
plt.savefig(f"figure-{ts}.png")