Python建立臨時檔案和資料夾
問題
你需要在程式執行時建立一個臨時檔案或目錄,並希望使用完之後可以自動銷燬掉。
解決方案
tempfile
模組中有很多的函式可以完成這任務。 為了建立一個匿名的臨時檔案,可以使用 tempfile.TemporaryFile
:
from tempfile import TemporaryFile with TemporaryFile('w+t') as f: # Read/write to the file f.write('Hello World\n') f.write('Testing\n') # Seek back to beginning and read the data f.seek(0) data = f.read() # Temporary file is destroyed
或者,如果你喜歡,你還可以像這樣使用臨時檔案:
f = TemporaryFile('w+t') # Use the temporary file ... f.close() # File is destroyed
TemporaryFile()
的第一個引數是檔案模式,通常來講文字模式使用 w+t
,二進位制模式使用 w+b
。 這個模式同時支援讀和寫操作,在這裡是很有用的,因為當你關閉檔案去改變模式的時候,檔案實際上已經不存在了。 TemporaryFile()
另外還支援跟內建的 open()
函式一樣的引數。比如:
with TemporaryFile('w+t',encoding='utf-8',errors='ignore') as f: ...
在大多數Unix系統上,通過 TemporaryFile()
建立的檔案都是匿名的,甚至連目錄都沒有。 如果你想打破這個限制,可以使用 NamedTemporaryFile()
來代替。比如:
from tempfile import NamedTemporaryFile with NamedTemporaryFile('w+t') as f: print('filename is:',f.name) ... # File automatically destroyed
這裡,被開啟檔案的 f.name
屬性包含了該臨時檔案的檔名。 當你需要將檔名傳遞給其他程式碼來開啟這個檔案的時候,這個就很有用了。 和 TemporaryFile()
delete=False
即可。比如:
with NamedTemporaryFile('w+t',delete=False) as f: print('filename is:',f.name) ...
為了建立一個臨時目錄,可以使用 tempfile.TemporaryDirectory()
。比如:
from tempfile import TemporaryDirectory with TemporaryDirectory() as dirname: print('dirname is:',dirname) # Use the directory ... # Directory and all contents destroyed
討論
TemporaryFile()
、NamedTemporaryFile()
和 TemporaryDirectory()
函式 應該是處理臨時檔案目錄的最簡單的方式了,因為它們會自動處理所有的建立和清理步驟。 在一個更低的級別,你可以使用 mkstemp()
和 mkdtemp()
來建立臨時檔案和目錄。比如:
>>> import tempfile >>> tempfile.mkstemp() (3,'/var/folders/7W/7WZl5sfZEF0pljrEB1UMWE+++TI/-Tmp-/tmp7fefhv') >>> tempfile.mkdtemp() '/var/folders/7W/7WZl5sfZEF0pljrEB1UMWE+++TI/-Tmp-/tmp5wvcv6' >>>
但是,這些函式並不會做進一步的管理了。 例如,函式 mkstemp()
僅僅就返回一個原始的OS檔案描述符,你需要自己將它轉換為一個真正的檔案物件。 同樣你還需要自己清理這些檔案。
通常來講,臨時檔案在系統預設的位置被建立,比如 /var/tmp
或類似的地方。 為了獲取真實的位置,可以使用 tempfile.gettempdir()
函式。比如:
>>> tempfile.gettempdir() '/var/folders/7W/7WZl5sfZEF0pljrEB1UMWE+++TI/-Tmp-' >>>
所有和臨時檔案相關的函式都允許你通過使用關鍵字引數 prefix
、suffix
和 dir
來自定義目錄以及命名規則。比如:
>>> f = NamedTemporaryFile(prefix='mytemp',suffix='.txt',dir='/tmp') >>> f.name '/tmp/mytemp8ee899.txt' >>>
最後還有一點,儘可能以最安全的方式使用 tempfile
模組來建立臨時檔案。 包括僅給當前使用者授權訪問以及在檔案建立過程中採取措施避免競態條件。 要注意的是不同的平臺可能會不一樣。因此你最好閱讀 官方文件 來了解更多的細節。
以上就是Python建立臨時檔案和資料夾的詳細內容,更多關於Python臨時檔案和資料夾的資料請關注我們其它相關文章!