简体   繁体   English

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

[英]Create a temporary file with unique name using Python 3?

I would like to create a temporary file with an specific name (and if its possible with an specific extension). 我想创建一个具有特定名称的临时文件(如果可能,可以使用特定的扩展名)。

Example: 例:

-mytempfile.txt
-mytempfile2.xml

I've been reading about tempfile library, but as far as I know I can only set the following parameters 我一直在阅读有关tempfile库的信息,但据我所知我只能设置以下参数

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

The most secure method to do what you are asking for is, as Dan points out there is no need to specify any name to the file, I am only using suffix and prefix as OP asked for it in the question. 做您所要求的最安全的方法是,正如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)

to understand more about the security aspects attached to this you can refer to this link 要了解有关此附件的安全性方面的更多信息,请参考此链接

well if you can't use os and are required to perform these actions then consider using the following code. 如果您不能使用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 will give you the complete path to the file eg as: a将为您提供文件的完整路径,例如:

'/tmp/mynamesomething.xml' '/tmp/mynamesomething.xml'

in case you don't want to delete the file in the end then use: 如果您不想最后删除文件,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM