簡體   English   中英

使用Python 3創建具有唯一名稱的臨時文件?

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

我想創建一個具有特定名稱的臨時文件(如果可能,可以使用特定的擴展名)。

例:

-mytempfile.txt
-mytempfile2.xml

我一直在閱讀有關tempfile庫的信息,但據我所知我只能設置以下參數

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

做您所要求的最安全的方法是,正如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)

要了解有關此附件的安全性方面的更多信息,請參考此鏈接

如果您不能使用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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM