使用tempfile创建所有临时文件的子目录

10 投票
2 回答
9540 浏览
提问于 2025-04-17 10:12

我一直在用 tempfile.mkdtemp 这个方法来创建临时文件,给它加了个前缀。这样一来,我的临时文件夹就会在 tmp 文件夹里生成很多不同的目录,格式是 'tmp/myprefix{uniq-string}/'。

我想改变这种情况,让这些临时文件夹都放在一个主目录下,也就是说,我希望前缀能变成 tmp 文件夹下的一个子文件夹,格式是 'tmp/myprefix/{uniq-string}/'。

另外,我不想改变 tempfile 默认的临时目录设置。

我尝试调整了 'prefix' 和 'dir' 这两个参数,但没有成功。

2 个回答

1

对我来说是可以的。你之前有创建过tmp文件夹吗?

>>> import tempfile
>>> tempfile.mkdtemp(dir="footest", prefix="fixpre")
OSError: [Errno 2] No such file or directory: 'footest/fixpregSSaFg'

看起来它确实在尝试创建一个footest的子文件夹……

15

要使用dir这个参数,你得确保dir文件夹是存在的。像下面这样应该就能正常工作:

import os
import tempfile

#define the location of 'mytemp' parent folder relative to the system temp
sysTemp = tempfile.gettempdir()
myTemp = os.path.join(sysTemp,'mytemp')

#You must make sure myTemp exists
if not os.path.exists(myTemp):
    os.makedirs(myTemp)

#now make your temporary sub folder
tempdir = tempfile.mkdtemp(suffix='foo',prefix='bar',dir=myTemp)

print tempdir

撰写回答