使用 Python 生成臨時檔案和目錄
標準庫中的 **tempfile** 模組定義了用於建立臨時檔案和目錄的函式。它們在由作業系統檔案系統定義的特殊臨時目錄中建立。例如,在 Windows 下,臨時資料夾位於 profile/AppData/Local/Temp 中,而在 Linux 中,臨時檔案儲存在 /tmp 目錄中。
以下函式在 tempfile 模組中定義
TemporaryFile()
此函式在臨時目錄中建立一個臨時檔案,並返回一個檔案物件,類似於內建的 open() 函式。預設情況下,該檔案以 wb+ 模式開啟,這意味著它可以同時用於讀取/寫入其中的二進位制資料。重要的是,檔案物件關閉後,臨時資料夾中的檔案條目將被刪除。以下程式碼顯示了 TemporaryFile() 函式的使用。
>>> import tempfile >>> f = tempfile.TemporaryFile() >>> f.write(b'Welcome to TutorialsPoint') >>> import os >>> f.seek(os.SEEK_SET) >>> f.read() b'Welcome to TutorialsPoint' >>> f.close()
以下示例以 w+ 模式開啟 TemporaryFile 物件以寫入然後讀取文字資料而不是二進位制資料。
>>> ff = tempfile.TemporaryFile(mode = 'w+')
>>> ff.write('hello world')
>>> ff.seek(0)
>>> ff.read()
'hello world'
>>> ff.close()NamedTemporaryFile()
此函式類似於 TemporaryFile() 函式。唯一的區別在於,具有隨機檔名的檔案在作業系統的指定臨時資料夾中可見。名稱可以透過檔案物件的 name 屬性檢索。此檔案在關閉後也會立即刪除。
>>> fo = tempfile.NamedTemporaryFile() >>> fo.name 'C:\Users\acer\AppData\Local\Temp\tmpipreok8q' >>> fo.close()
TemporaryDirectory()
此函式建立一個臨時目錄。您可以透過提及 dir 引數來選擇此臨時目錄的位置。以下語句將在 C:\python36 資料夾中建立一個臨時目錄。
>>> f = tempfile.TemporaryDirectory(dir = "C:/python36") <TemporaryDirectory 'C:/python36\ tmp9wrjtxc_'>
建立的目錄出現在 dir1 資料夾中。透過在目錄物件上呼叫 cleanup() 函式將其刪除。
>>> f.name 'C:/python36\tmp9wrjtxc_' >>> f.cleanup()
mkstemp()
此函式還建立了一個臨時檔案,類似於 TemporaryFile() 函式。此外,suffix 和 prefix 引數可用於新增到建立的臨時檔案中。與 TemporaryFile() 不同,建立的檔案不會自動刪除。它應該手動刪除。
>>> f = tempfile.mkstemp(suffix = '.tp') C:\Users\acer\AppData\Local\Temp\tmpbljk6ku8.tp
mkdtemp()
此函式還在作業系統的臨時資料夾中建立一個臨時目錄,並返回其絕對路徑名。要顯式定義其建立位置,請使用 dir 引數。此資料夾也不會自動刪除。
>>> tempfile.mkdtemp(dir = "c:/python36") 'c:/python36\tmpruxmm66u'
gettempdir()
此函式返回儲存臨時檔案的目錄名稱。此名稱通常從 tempdir 環境變數中獲取。在 Windows 平臺上,它通常是 user/AppData/Local/Temp 或 windowsdir/temp 或 systemdrive/temp。在 Linux 上,它通常是 /tmp。此目錄用作 dir 引數的預設值。
>>> tempfile.gettempdir() 'C:\Users\acer\AppData\Local\Temp'
在本文中,解釋了 tempfile 模組中的函式。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP