繁体   English   中英

如何使用不同的名称保存文件,而不是覆盖现有文件

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

我需要在不同的数据集上重复运行python脚本。 此python脚本test.py使用该命令处理数据集,绘制并保存结果。

plt.savefig('result.png')

当相同的test.py脚本在另一个数据集上运行时,如何确保新的result.png不会覆盖以前的结果? 基本上在执行plt.savefig('result.png') ,我需要检查result.png是否已经存在,如果是,则将结果重命名为任何其他名称,如

result1.png
result2.png

否则,在下一个后处理中,文件将被覆盖。

您可以使用os.path.exists检查文件是否已存在,如果存在,则附加一个数字。 重复使用新文件名,直到找到尚不存在的文件名。

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

实施例使用状态:

for i in range(5):
    with open(unique_file("foo", "txt"), "w") as f:
        f.write(str(i))
import time
if os.path.exists('result.png'):
    plt.savefig('result_{}.png'.format(int(time.time())))
else:
    plt.savefig('result.png')

您可以使用标准库中提供的tempfile.mkstemp

import tempfile
fi, filename = tempfile.mkstemp(prefix='result_', suffix='.png')

注意: fi是一个整数。 如果你需要一个文件对象呢

f = os.fdopen(fi, "w")

filename包括创建文件的绝对路径名,例如

'/tmp/result_d_3787js.png'

另一种解决方案是使用UUID,例如

import uuid
filename = 'result_'+str(uuid.uuid4())+'.png'

产生类似的东西

result_cf29d123-271e-4899-b2f6-d172f157af65.png

有关mkstempuuid的更多信息和参数,请参阅官方文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM