如何用不同的名称保存文件而不覆盖

2024-09-28 16:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在不同的数据集上重复运行一个python脚本。python脚本test.py使用命令处理数据集、打印和保存结果。

plt.savefig('result.png')

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

result1.png
result2.png

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


Tags: 文件数据pytest命令脚本名称png
3条回答

您可以使用标准库中的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

您可以使用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')

相关问题 更多 >