我需要使用自定义名称创建一个 NamedTemporaryFile。
我尝试设置名称属性,但没有奏效。
from tempfile import NamedTemporaryFile
f = NamedTemporaryFile(dir='/tmp/')
f.name = custom_name
当我尝试使用时,文件名没有改变os.path.exists
,它为旧名称返回 true。
我已经查看了自定义名称的临时文件/目录?,但创建一个临时目录不适合我的用例。
我需要使用自定义名称创建一个 NamedTemporaryFile。
我尝试设置名称属性,但没有奏效。
from tempfile import NamedTemporaryFile
f = NamedTemporaryFile(dir='/tmp/')
f.name = custom_name
当我尝试使用时,文件名没有改变os.path.exists
,它为旧名称返回 true。
我已经查看了自定义名称的临时文件/目录?,但创建一个临时目录不适合我的用例。
NamedTemporaryFile没有name
参数。名称由 生成tempfile._get_candidate_names
。可以对此进行修补并提供您自己的名称。但是,您可以为生成的名称添加前缀和后缀,从而使至少部分名称可预测:
Python 3.6.9 (default, Nov 23 2019, 06:49:55)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from tempfile import NamedTemporaryFile
In [2]: file = NamedTemporaryFile(prefix='asdf_', mode='w+', suffix='.xlsx')
In [3]: file.name
Out[3]: '/tmp/asdf_uskygtov.xlsx'
这是猴子补丁的示例:
Python 3.6.9 (default, Nov 23 2019, 06:49:55)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import tempfile
In [2]: import itertools
In [3]: tempfile._get_candidate_names = lambda: itertools.repeat('my_file')
In [4]: file = tempfile.NamedTemporaryFile(mode='w+', prefix='', suffix='txt')
In [5]: file.name
Out[5]: '/tmp/my_filetxt'
In [6]: file = tempfile.NamedTemporaryFile(mode='w+', prefix='', suffix='.txt')
In [7]: file.name
Out[7]: '/tmp/my_file.txt'