使用Python 3创建具有唯一名称的临时文件?

时间:2018-08-09 21:07:23

标签: python python-3.x file temp

我想创建一个具有特定名称的临时文件(如果可能,可以使用特定的扩展名)。

示例:

-mytempfile.txt
-mytempfile2.xml

我一直在阅读有关tempfile库的信息,但据我所知,我只能设置以下参数

(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

1 个答案:

答案 0 :(得分:4)

要做的最安全的方法是,因为Dan指出不需要为文件指定任何名称,我只使用后缀和前缀作为问题中要求它的OP。

import os
import tempfile as tfile
fd, path = tfile.mkstemp(suffix=".txt",prefix="abc") #can use anything 
try:
    with os.fdopen(fd, 'w') as tmpo:
        # do stuff with temp file
        tmpo.write('something here')
finally:
    os.remove(path)

要了解有关此安全性方面的更多信息,可以参考此link

好吧,如果您不能使用os并且需要执行这些操作,那么请考虑使用以下代码。

import tempfile as tfile
temp_file=tfile.NamedTemporaryFile(mode="w",suffix=".xml",prefix="myname")
a=temp_file.name

temp_file.write("12")
temp_file.close()

a将为您提供文件的完整路径,例如:

  

'/ tmp / mynamesomething.xml'

如果您不想最后删除文件,请使用:

temp_file=tfile.NamedTemporaryFile(delete=False) #along with other parameters of course.
相关问题