python – 使用tempfile为我的所有临时文件创建一个子目录

我一直在使用带有前缀的tempfile.mkdtemp来创建我的临时文件.这导致我的tmp文件夹中有很多不同的目录,其中包含’tmp / myprefix {uniq-string} /’.

我想更改它并有一个子目录,以便我创建的临时文件夹都在一个主目录下,这样前缀实际上是tmp’tmp / myprefix / {uniq-string} /’的子文件夹.

另外,我不想覆盖tempfile的系统来定义默认的tmp目录.

我尝试使用’prefix’和’dir’参数但没有成功.

最佳答案
要使用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

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...