我想创建一个临时文件与一个特定的名称(如果可能的话,与一个特定的扩展名)。
示例:
-mytempfile.txt
-mytempfile2.xml
我一直在阅读有关tempfile库的内容,但据我所知,我只能设置以下参数
(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)
发布于 2018-08-10 05:13:02
要做到你所要求的,最安全的方法是,正如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.
https://stackoverflow.com/questions/51775775
复制相似问题