tempfile
--- 生成臨時文件和目錄?
源代碼: Lib/tempfile.py
該模塊用于創(chuàng)建臨時文件和目錄,它可以跨平臺使用。TemporaryFile
、NamedTemporaryFile
、TemporaryDirectory
和 SpooledTemporaryFile
是帶有自動清理功能的高級接口,可用作上下文管理器。mkstemp()
和 mkdtemp()
是低級函數(shù),使用完畢需手動清理。
所有由用戶調(diào)用的函數(shù)和構(gòu)造函數(shù)都帶有參數(shù),這些參數(shù)可以設(shè)置臨時文件和臨時目錄的路徑和名稱。該模塊生成的文件名包括一串隨機(jī)字符,在公共的臨時目錄中,這些字符可以讓創(chuàng)建文件更加安全。為了保持向后兼容性,參數(shù)的順序有些奇怪。所以為了代碼清晰,建議使用關(guān)鍵字參數(shù)。
這個模塊定義了以下內(nèi)容供用戶調(diào)用:
- tempfile.TemporaryFile(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)?
返回一個 file-like object (文件類對象)作為臨時存儲區(qū)域。創(chuàng)建該文件使用了與
mkstemp()
相同的安全規(guī)則。它將在關(guān)閉后立即銷毀(包括垃圾回收機(jī)制關(guān)閉該對象時)。在 Unix 下,該文件在目錄中的條目根本不創(chuàng)建,或者創(chuàng)建文件后立即就被刪除了,其他平臺不支持此功能。您的代碼不應(yīng)依賴使用此功能創(chuàng)建的臨時文件名稱,因為它在文件系統(tǒng)中的名稱可能是可見的,也可能是不可見的。生成的對象可以用作上下文管理器(參見 例子)。完成上下文或銷毀臨時文件對象后,臨時文件將從文件系統(tǒng)中刪除。
mode 參數(shù)默認(rèn)值為
'w+b'
,所以創(chuàng)建的文件不用關(guān)閉,就可以讀取或?qū)懭?。因為用的是二進(jìn)制模式,所以無論存的是什么數(shù)據(jù),它在所有平臺上都表現(xiàn)一致。buffering、encoding、errors 和 newline 的含義與open()
中的相同。參數(shù) dir、prefix 和 suffix 的含義和默認(rèn)值都與它們在
mkstemp()
中的相同。在 POSIX 平臺上,它返回的對象是真實的文件對象。在其他平臺上,它是一個文件類對象 (file-like object),它的
file
屬性是底層的真實文件對象。如果可用,則使用
os.O_TMPFILE
標(biāo)志(僅限于 Linux,需要 3.11 及更高版本的內(nèi)核)。On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias for NamedTemporaryFile.
引發(fā)一個
tempfile.mkstemp
審計事件,附帶參數(shù)fullpath
。在 3.5 版更改: 如果可用,現(xiàn)在用的是
os.O_TMPFILE
標(biāo)志。在 3.8 版更改: 添加了 errors 參數(shù)。
- tempfile.NamedTemporaryFile(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None)?
This function operates exactly as
TemporaryFile()
does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from thename
attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows). If delete is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whosefile
attribute is the underlying true file object. This file-like object can be used in awith
statement, just like a normal file.On POSIX (only), a process that is terminated abruptly with SIGKILL cannot automatically delete any NamedTemporaryFiles it created.
引發(fā)一個
tempfile.mkstemp
審計事件,附帶參數(shù)fullpath
。在 3.8 版更改: 添加了 errors 參數(shù)。
- class tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)?
This class operates exactly as
TemporaryFile()
does, except that data is spooled in memory until the file size exceeds max_size, or until the file'sfileno()
method is called, at which point the contents are written to disk and operation proceeds as withTemporaryFile()
.此函數(shù)生成的文件對象有一個額外的方法——
rollover()
,可以忽略文件大小,讓文件立即寫入磁盤。返回的對象是文件類對象 (file-like object),它的
_file
屬性是io.BytesIO
或io.TextIOWrapper
對象(取決于指定的是二進(jìn)制模式還是文本模式)或真實的文件對象(取決于是否已調(diào)用rollover()
)。文件類對象可以像普通文件一樣在with
語句中使用。在 3.3 版更改: 現(xiàn)在,文件的 truncate 方法可接受一個
size
參數(shù)。在 3.8 版更改: 添加了 errors 參數(shù)。
在 3.11 版更改: Fully implements the
io.BufferedIOBase
andio.TextIOBase
abstract base classes (depending on whether binary or text mode was specified).
- class tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False)?
This class securely creates a temporary directory using the same rules as
mkdtemp()
. The resulting object can be used as a context manager (see 例子). On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.可以從返回對象的
name
屬性中找到臨時目錄的名稱。當(dāng)返回的對象用作上下文管理器時,這個name
會作為with
語句中as
子句的目標(biāo)(如果有 as 的話)。此目錄可通過調(diào)用
cleanup()
方法來顯式地清理。 如果 ignore_cleanup_errors 為真值,則在顯式或隱式清理(例如在 Windows 上PermissionError
移除打開的文件)期間出現(xiàn)的未處理異常將被忽略,并且剩余的可移除條目會被“盡可能”地刪除。 在其他情況下,錯誤將在任何上下文清理發(fā)生時被引發(fā) (cleanup()
調(diào)用、退出上下文管理器、對象被作為垃圾回收或解釋器關(guān)閉等)。引發(fā)一個
tempfile.mkdtemp
審計事件,附帶參數(shù)fullpath
。3.2 新版功能.
在 3.10 版更改: 添加了 ignore_cleanup_errors 形參。
- tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)?
以最安全的方式創(chuàng)建一個臨時文件。假設(shè)所在平臺正確實現(xiàn)了
os.open()
的os.O_EXCL
標(biāo)志,則創(chuàng)建文件時不會有競爭的情況。該文件只能由創(chuàng)建者讀寫,如果所在平臺用權(quán)限位來標(biāo)記文件是否可執(zhí)行,那么沒有人有執(zhí)行權(quán)。文件描述符不會過繼給子進(jìn)程。與
TemporaryFile()
不同,mkstemp()
用戶用完臨時文件后需要自行將其刪除。如果 suffix 不是
None
則文件名將以該后綴結(jié)尾,是None
則沒有后綴。mkstemp()
不會在文件名和后綴之間加點,如果需要加一個點號,請將其放在 suffix 的開頭。如果 prefix 不是
None
,則文件名將以該前綴開頭,是None
則使用默認(rèn)前綴。默認(rèn)前綴是gettempprefix()
或gettempprefixb()
函數(shù)的返回值(自動調(diào)用合適的函數(shù))。如果 dir 不為
None
,則在指定的目錄創(chuàng)建文件,是None
則使用默認(rèn)目錄。默認(rèn)目錄是從一個列表中選擇出來的,這個列表不同平臺不一樣,但是用戶可以設(shè)置 TMPDIR、TEMP 或 TMP 環(huán)境變量來設(shè)置目錄的位置。因此,不能保證生成的臨時文件路徑很規(guī)范,比如,通過os.popen()
將路徑傳遞給外部命令時仍需要加引號。如果 suffix、prefix 和 dir 中的任何一個不是
None
,就要保證它們是同一數(shù)據(jù)類型。如果它們是 bytes,則返回的名稱的類型就是 bytes 而不是 str。如果確實要用默認(rèn)參數(shù),但又想要返回值是 bytes 類型,請傳入suffix=b''
。如果指定了 text 且為真值,文件會以文本模式打開。 否則,文件(默認(rèn))會以二進(jìn)制模式打開。
mkstemp()
返回一個元組,元組中第一個元素是句柄,它是一個系統(tǒng)級句柄,指向一個打開的文件(等同于os.open()
的返回值),第二元素是該文件的絕對路徑。引發(fā)一個
tempfile.mkstemp
審計事件,附帶參數(shù)fullpath
。在 3.5 版更改: 現(xiàn)在,suffix、prefix 和 dir 可以以 bytes 類型按順序提供,以獲得 bytes 類型的返回值。之前只允許使用 str。suffix 和 prefix 現(xiàn)在可以接受
None
,并且默認(rèn)為None
以使用合適的默認(rèn)值。在 3.6 版更改: dir 參數(shù)現(xiàn)在可接受一個路徑類對象 (path-like object)。
- tempfile.mkdtemp(suffix=None, prefix=None, dir=None)?
以最安全的方式創(chuàng)建一個臨時目錄,創(chuàng)建該目錄時不會有競爭的情況。該目錄只能由創(chuàng)建者讀取、寫入和搜索。
mkdtemp()
用戶用完臨時目錄后需要自行將其刪除。prefix、suffix 和 dir 的含義與它們在
mkstemp()
中的相同。mkdtemp()
返回新目錄的絕對路徑。引發(fā)一個
tempfile.mkdtemp
審計事件,附帶參數(shù)fullpath
。在 3.5 版更改: 現(xiàn)在,suffix、prefix 和 dir 可以以 bytes 類型按順序提供,以獲得 bytes 類型的返回值。之前只允許使用 str。suffix 和 prefix 現(xiàn)在可以接受
None
,并且默認(rèn)為None
以使用合適的默認(rèn)值。在 3.6 版更改: dir 參數(shù)現(xiàn)在可接受一個路徑類對象 (path-like object)。
- tempfile.gettempdir()?
返回放置臨時文件的目錄的名稱。這個方法的返回值就是本模塊所有函數(shù)的 dir 參數(shù)的默認(rèn)值。
Python 搜索標(biāo)準(zhǔn)目錄列表,以找到調(diào)用者可以在其中創(chuàng)建文件的目錄。這個列表是:
TMPDIR
環(huán)境變量指向的目錄。TEMP
環(huán)境變量指向的目錄。TMP
環(huán)境變量指向的目錄。與平臺相關(guān)的位置:
在 Windows 上,依次為
C:\TEMP
、C:\TMP
、\TEMP
和\TMP
。在所有其他平臺上,依次為
/tmp
、/var/tmp
和/usr/tmp
。
不得已時,使用當(dāng)前工作目錄。
搜索的結(jié)果會緩存起來,參見下面
tempdir
的描述。在 3.10 版更改: 總是返回一個字符串。 在之前的版本中它會返回任意
tempdir
值而不考慮它的類型,只要它不為None
。
- tempfile.gettempdirb()?
與
gettempdir()
相同,但返回值為字節(jié)類型。3.5 新版功能.
- tempfile.gettempprefix()?
返回用于創(chuàng)建臨時文件的文件名前綴,它不包含目錄部分。
- tempfile.gettempprefixb()?
與
gettempprefix()
相同,但返回值為字節(jié)類型。3.5 新版功能.
本模塊使用一個全局變量來存儲由 gettempdir()
返回的臨時文件使用的目錄路徑。 它可被直接設(shè)置以覆蓋選擇過程,但不建議這樣做。 本模塊中的所有函數(shù)都接受一個 dir 參數(shù),它可被用于指定目錄。 這是不會通過改變?nèi)?API 行為對其他無準(zhǔn)備代碼造成影響的推薦做法。
- tempfile.tempdir?
當(dāng)設(shè)為
None
以外的值時,此變量會為本模塊中定義的函數(shù)的 dir 參數(shù)定義默認(rèn)值,包括確定其類型為字節(jié)串還是字符串。 它不可以為 path-like object。如果在調(diào)用除
gettempprefix()
外的上述任何函數(shù)時tempdir
為None
(默認(rèn)值) 則它會按照gettempdir()
中所描述的算法來初始化。
例子?
以下是 tempfile
模塊典型用法的一些示例:
>>> import tempfile
# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()
# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
... fp.write(b'Hello world!')
... fp.seek(0)
... fp.read()
b'Hello world!'
>>>
# file is now closed and removed
# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
... print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed
已棄用的函數(shù)和變量?
創(chuàng)建臨時文件有一種歷史方法,首先使用 mktemp()
函數(shù)生成一個文件名,然后使用該文件名創(chuàng)建文件。不幸的是,這是不安全的,因為在調(diào)用 mktemp()
與隨后嘗試創(chuàng)建文件的進(jìn)程之間的時間里,其他進(jìn)程可能會使用該名稱創(chuàng)建文件。解決方案是將兩個步驟結(jié)合起來,立即創(chuàng)建文件。這個方案目前被 mkstemp()
和上述其他函數(shù)所采用。
- tempfile.mktemp(suffix='', prefix='tmp', dir=None)?
2.3 版后已移除: 使用
mkstemp()
來代替。返回一個絕對路徑,這個路徑指向的文件在調(diào)用本方法時不存在。prefix、suffix 和 dir 參數(shù)與
mkstemp()
中的同名參數(shù)類似,不同之處在于不支持字節(jié)類型的文件名,不支持suffix=None
和prefix=None
。警告
使用此功能可能會在程序中引入安全漏洞。當(dāng)你開始使用本方法返回的文件執(zhí)行任何操作時,可能有人已經(jīng)捷足先登了。
mktemp()
的功能可以很輕松地用NamedTemporaryFile()
代替,當(dāng)然需要傳遞delete=False
參數(shù):>>> f = NamedTemporaryFile(delete=False) >>> f.name '/tmp/tmptjujjt' >>> f.write(b"Hello World!\n") 13 >>> f.close() >>> os.unlink(f.name) >>> os.path.exists(f.name) False