Create a temporary file with unique name using Python 3?

jaj*_*jdp 1 python file temp python-3.x

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
Run Code Online (Sandbox Code Playgroud)

I've been reading about tempfile library, but as far as I know I can only set the following parameters

(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)
Run Code Online (Sandbox Code Playgroud)

Ind*_*der 6

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.

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)
Run Code Online (Sandbox Code Playgroud)

to understand more about the security aspects attached to this you can refer to this 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()
Run Code Online (Sandbox Code Playgroud)

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

'/tmp/mynamesomething.xml'

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

temp_file=tfile.NamedTemporaryFile(delete=False) #along with other parameters of course.
Run Code Online (Sandbox Code Playgroud)