tempfile --- 生成臨時(shí)文件和目錄?

源代碼: Lib/tempfile.py


該模塊用于創(chuàng)建臨時(shí)文件和目錄,它可以跨平臺(tái)使用。TemporaryFile、NamedTemporaryFile、TemporaryDirectorySpooledTemporaryFile 是帶有自動(dòng)清理功能的高級(jí)接口,可用作上下文管理器。mkstemp()mkdtemp() 是低級(jí)函數(shù),使用完畢需手動(dòng)清理。

所有由用戶調(diào)用的函數(shù)和構(gòu)造函數(shù)都帶有參數(shù),這些參數(shù)可以設(shè)置臨時(shí)文件和臨時(shí)目錄的路徑和名稱。該模塊生成的文件名包括一串隨機(jī)字符,在公共的臨時(shí)目錄中,這些字符可以讓創(chuàng)建文件更加安全。為了保持向后兼容性,參數(shù)的順序有些奇怪。所以為了代碼清晰,建議使用關(guān)鍵字參數(shù)。

這個(gè)模塊定義了以下內(nèi)容供用戶調(diào)用:

tempfile.TemporaryFile(mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)?

返回一個(gè) file-like object (文件類對(duì)象)作為臨時(shí)存儲(chǔ)區(qū)域。創(chuàng)建該文件使用了與 mkstemp() 相同的安全規(guī)則。它將在關(guān)閉后立即銷毀(包括垃圾回收機(jī)制關(guān)閉該對(duì)象時(shí))。在 Unix 下,該文件在目錄中的條目根本不創(chuàng)建,或者創(chuàng)建文件后立即就被刪除了,其他平臺(tái)不支持此功能。您的代碼不應(yīng)依賴使用此功能創(chuàng)建的臨時(shí)文件名稱,因?yàn)樗谖募到y(tǒng)中的名稱可能是可見的,也可能是不可見的。

生成的對(duì)象可以用作上下文管理器(參見 例子)。完成上下文或銷毀臨時(shí)文件對(duì)象后,臨時(shí)文件將從文件系統(tǒng)中刪除。

mode 參數(shù)默認(rèn)值為 'w+b',所以創(chuàng)建的文件不用關(guān)閉,就可以讀取或?qū)懭搿R驗(yàn)橛玫氖嵌M(jìn)制模式,所以無論存的是什么數(shù)據(jù),它在所有平臺(tái)上都表現(xiàn)一致。buffering、encodingerrorsnewline 的含義與 open() 中的相同。

參數(shù) dirprefixsuffix 的含義和默認(rèn)值都與它們?cè)?mkstemp() 中的相同。

在 POSIX 平臺(tái)上,它返回的對(duì)象是真實(shí)的文件對(duì)象。在其他平臺(tái)上,它是一個(gè)文件類對(duì)象 (file-like object),它的 file 屬性是底層的真實(shí)文件對(duì)象。

如果可用,則使用 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ā)一個(gè) tempfile.mkstemp 審計(jì)事件,附帶參數(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 the name 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 whose file attribute is the underlying true file object. This file-like object can be used in a with 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ā)一個(gè) tempfile.mkstemp 審計(jì)事件,附帶參數(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's fileno() method is called, at which point the contents are written to disk and operation proceeds as with TemporaryFile().

此函數(shù)生成的文件對(duì)象有一個(gè)額外的方法——rollover(),可以忽略文件大小,讓文件立即寫入磁盤。

返回的對(duì)象是文件類對(duì)象 (file-like object),它的 _file 屬性是 io.BytesIOio.TextIOWrapper 對(duì)象(取決于指定的是二進(jìn)制模式還是文本模式)或真實(shí)的文件對(duì)象(取決于是否已調(diào)用 rollover())。文件類對(duì)象可以像普通文件一樣在 with 語句中使用。

在 3.3 版更改: 現(xiàn)在,文件的 truncate 方法可接受一個(gè) size 參數(shù)。

在 3.8 版更改: 添加了 errors 參數(shù)。

在 3.11 版更改: Fully implements the io.BufferedIOBase and io.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.

可以從返回對(duì)象的 name 屬性中找到臨時(shí)目錄的名稱。當(dāng)返回的對(duì)象用作上下文管理器時(shí),這個(gè) name 會(huì)作為 with 語句中 as 子句的目標(biāo)(如果有 as 的話)。

此目錄可通過調(diào)用 cleanup() 方法來顯式地清理。 如果 ignore_cleanup_errors 為真值,則在顯式或隱式清理(例如在 Windows 上 PermissionError 移除打開的文件)期間出現(xiàn)的未處理異常將被忽略,并且剩余的可移除條目會(huì)被“盡可能”地刪除。 在其他情況下,錯(cuò)誤將在任何上下文清理發(fā)生時(shí)被引發(fā) (cleanup() 調(diào)用、退出上下文管理器、對(duì)象被作為垃圾回收或解釋器關(guān)閉等)。

引發(fā)一個(gè) tempfile.mkdtemp 審計(jì)事件,附帶參數(shù) fullpath。

3.2 新版功能.

在 3.10 版更改: 添加了 ignore_cleanup_errors 形參。

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)?

以最安全的方式創(chuàng)建一個(gè)臨時(shí)文件。假設(shè)所在平臺(tái)正確實(shí)現(xiàn)了 os.open()os.O_EXCL 標(biāo)志,則創(chuàng)建文件時(shí)不會(huì)有競爭的情況。該文件只能由創(chuàng)建者讀寫,如果所在平臺(tái)用權(quán)限位來標(biāo)記文件是否可執(zhí)行,那么沒有人有執(zhí)行權(quán)。文件描述符不會(huì)過繼給子進(jìn)程。

TemporaryFile() 不同,mkstemp() 用戶用完臨時(shí)文件后需要自行將其刪除。

如果 suffix 不是 None 則文件名將以該后綴結(jié)尾,是 None 則沒有后綴。mkstemp() 不會(huì)在文件名和后綴之間加點(diǎn),如果需要加一個(gè)點(diǎn)號(hào),請(qǐng)將其放在 suffix 的開頭。

如果 prefix 不是 None,則文件名將以該前綴開頭,是 None 則使用默認(rèn)前綴。默認(rèn)前綴是 gettempprefix()gettempprefixb() 函數(shù)的返回值(自動(dòng)調(diào)用合適的函數(shù))。

如果 dir 不為 None,則在指定的目錄創(chuàng)建文件,是 None 則使用默認(rèn)目錄。默認(rèn)目錄是從一個(gè)列表中選擇出來的,這個(gè)列表不同平臺(tái)不一樣,但是用戶可以設(shè)置 TMPDIR、TEMPTMP 環(huán)境變量來設(shè)置目錄的位置。因此,不能保證生成的臨時(shí)文件路徑很規(guī)范,比如,通過 os.popen() 將路徑傳遞給外部命令時(shí)仍需要加引號(hào)。

如果 suffix、prefixdir 中的任何一個(gè)不是 None,就要保證它們是同一數(shù)據(jù)類型。如果它們是 bytes,則返回的名稱的類型就是 bytes 而不是 str。如果確實(shí)要用默認(rèn)參數(shù),但又想要返回值是 bytes 類型,請(qǐng)傳入 suffix=b''。

如果指定了 text 且為真值,文件會(huì)以文本模式打開。 否則,文件(默認(rèn))會(huì)以二進(jìn)制模式打開。

mkstemp() 返回一個(gè)元組,元組中第一個(gè)元素是句柄,它是一個(gè)系統(tǒng)級(jí)句柄,指向一個(gè)打開的文件(等同于 os.open() 的返回值),第二元素是該文件的絕對(duì)路徑。

引發(fā)一個(gè) tempfile.mkstemp 審計(jì)事件,附帶參數(shù) fullpath。

在 3.5 版更改: 現(xiàn)在,suffixprefixdir 可以以 bytes 類型按順序提供,以獲得 bytes 類型的返回值。之前只允許使用 str。suffixprefix 現(xiàn)在可以接受 None,并且默認(rèn)為 None 以使用合適的默認(rèn)值。

在 3.6 版更改: dir 參數(shù)現(xiàn)在可接受一個(gè)路徑類對(duì)象 (path-like object)。

tempfile.mkdtemp(suffix=None, prefix=None, dir=None)?

以最安全的方式創(chuàng)建一個(gè)臨時(shí)目錄,創(chuàng)建該目錄時(shí)不會(huì)有競爭的情況。該目錄只能由創(chuàng)建者讀取、寫入和搜索。

mkdtemp() 用戶用完臨時(shí)目錄后需要自行將其刪除。

prefixsuffixdir 的含義與它們?cè)?mkstemp() 中的相同。

mkdtemp() 返回新目錄的絕對(duì)路徑。

引發(fā)一個(gè) tempfile.mkdtemp 審計(jì)事件,附帶參數(shù) fullpath。

在 3.5 版更改: 現(xiàn)在,suffixprefixdir 可以以 bytes 類型按順序提供,以獲得 bytes 類型的返回值。之前只允許使用 str。suffixprefix 現(xiàn)在可以接受 None,并且默認(rèn)為 None 以使用合適的默認(rèn)值。

在 3.6 版更改: dir 參數(shù)現(xiàn)在可接受一個(gè)路徑類對(duì)象 (path-like object)。

tempfile.gettempdir()?

返回放置臨時(shí)文件的目錄的名稱。這個(gè)方法的返回值就是本模塊所有函數(shù)的 dir 參數(shù)的默認(rèn)值。

Python 搜索標(biāo)準(zhǔn)目錄列表,以找到調(diào)用者可以在其中創(chuàng)建文件的目錄。這個(gè)列表是:

  1. TMPDIR 環(huán)境變量指向的目錄。

  2. TEMP 環(huán)境變量指向的目錄。

  3. TMP 環(huán)境變量指向的目錄。

  4. 與平臺(tái)相關(guān)的位置:

    • 在 Windows 上,依次為 C:\TEMP、C:\TMP、\TEMP\TMP。

    • 在所有其他平臺(tái)上,依次為 /tmp、/var/tmp/usr/tmp。

  5. 不得已時(shí),使用當(dāng)前工作目錄。

搜索的結(jié)果會(huì)緩存起來,參見下面 tempdir 的描述。

在 3.10 版更改: 總是返回一個(gè)字符串。 在之前的版本中它會(huì)返回任意 tempdir 值而不考慮它的類型,只要它不為 None。

tempfile.gettempdirb()?

gettempdir() 相同,但返回值為字節(jié)類型。

3.5 新版功能.

tempfile.gettempprefix()?

返回用于創(chuàng)建臨時(shí)文件的文件名前綴,它不包含目錄部分。

tempfile.gettempprefixb()?

gettempprefix() 相同,但返回值為字節(jié)類型。

3.5 新版功能.

本模塊使用一個(gè)全局變量來存儲(chǔ)由 gettempdir() 返回的臨時(shí)文件使用的目錄路徑。 它可被直接設(shè)置以覆蓋選擇過程,但不建議這樣做。 本模塊中的所有函數(shù)都接受一個(gè) dir 參數(shù),它可被用于指定目錄。 這是不會(huì)通過改變?nèi)?API 行為對(duì)其他無準(zhǔn)備代碼造成影響的推薦做法。

tempfile.tempdir?

當(dāng)設(shè)為 None 以外的值時(shí),此變量會(huì)為本模塊中定義的函數(shù)的 dir 參數(shù)定義默認(rèn)值,包括確定其類型為字節(jié)串還是字符串。 它不可以為 path-like object

如果在調(diào)用除 gettempprefix() 外的上述任何函數(shù)時(shí) tempdirNone (默認(rèn)值) 則它會(huì)按照 gettempdir() 中所描述的算法來初始化。

備注

請(qǐng)注意如果你將 tempdir 設(shè)為字節(jié)串值,會(huì)有一個(gè)麻煩的副作用: mkstemp()mkdtemp() 的全局默認(rèn)返回類型會(huì)在沒有顯式提供字符串類型的when no explicit prefix, suffixdir 的時(shí)候被改為字節(jié)串。 請(qǐng)不要編寫預(yù)期或依賴于此入圍的代碼。 這個(gè)笨拙行為是為了保持與歷史實(shí)現(xiàn)的兼容性。

例子?

以下是 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)建臨時(shí)文件有一種歷史方法,首先使用 mktemp() 函數(shù)生成一個(gè)文件名,然后使用該文件名創(chuàng)建文件。不幸的是,這是不安全的,因?yàn)樵谡{(diào)用 mktemp() 與隨后嘗試創(chuàng)建文件的進(jìn)程之間的時(shí)間里,其他進(jìn)程可能會(huì)使用該名稱創(chuàng)建文件。解決方案是將兩個(gè)步驟結(jié)合起來,立即創(chuàng)建文件。這個(gè)方案目前被 mkstemp() 和上述其他函數(shù)所采用。

tempfile.mktemp(suffix='', prefix='tmp', dir=None)?

2.3 版后已移除: 使用 mkstemp() 來代替。

返回一個(gè)絕對(duì)路徑,這個(gè)路徑指向的文件在調(diào)用本方法時(shí)不存在。prefix、suffixdir 參數(shù)與 mkstemp() 中的同名參數(shù)類似,不同之處在于不支持字節(jié)類型的文件名,不支持 suffix=Noneprefix=None。

警告

使用此功能可能會(huì)在程序中引入安全漏洞。當(dāng)你開始使用本方法返回的文件執(zhí)行任何操作時(shí),可能有人已經(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