6.6.6 临时文件位置
如果没有使用dir参数指定明确的目标位置,则临时文件使用的路径会根据当前平台和设置而变化。tempfile模块包含两个函数来查询运行时使用的设置。
import tempfile
print('gettempdir():',tempfile.gettempdir())
print('gettempprefix():',tempfile.gettempprefix())
gettempdir()返回包含所有临时文件的默认目录,gettempprefix()返回新文件和目录名的字符串前缀。
运行结果:
gettempdir(): C:\Users\ADMINI~1\AppData\Local\Temp
gettempprefix(): tmp
gettempdir()返回的值根据一个简单算法来设置,它会查找一个位置列表,寻找第一个允许当前进程创建文件的位置。搜索列表的顺序如下:
1.环境变量TMPDIR。
2.环境变量TEMP。
3.环境变量TMP。
4.作为“后路”的位置,这取决于平台(Windows使用C:\temp、C:\tmp、\temp或\tmp中第一个可用的位置。其他平台使用/TMP,/var/tmp或/usr/tmp)。
5.如果找不到其他目录,则使用当前工作目录。
import tempfile
tempfile.tempdir = '/I/changed/this/path'
print('gettempdir():',tempfile.gettempdir())
如果程序需要对所有临时文件使用一个全局位置,但不使用以上任何环境变量,则应当直接设置tempfile.tempdir,为该变量赋一个值。
运行结果:
gettempdir(): /I/changed/this/path