1. 程式人生 > >python 建立臨時檔案和資料夾

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)
...

 

----被開啟檔案的f.name 屬性包含了該臨時檔案的檔名。當你需要將檔名傳遞給其他程式碼來開啟這個檔案的時候,這個就很有用了。和TemporaryFile() 一樣,結果檔案關閉時會被自動刪除掉。如果你不想這麼做,可以傳遞一個關鍵字引數delte=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 模組來建立臨時檔案。包括僅給當前使用者授權訪問以及在檔案建立過程中採取措施避免競態條件。要注意的是不同的平臺可能會不一樣。因此你最好閱讀官方文件來了解更多的細節。