Skip to content

[Python] 使用 tempfile 模組建立臨時工作目錄,並在工作流程結束後自動刪除

介紹

今天在閱讀 DreamBooth 訓練原始碼時,發現了 tempfile 這個模組;剛巧手邊又在做一個模型分層合併的的腳本改寫,頓時想到使用這個模組的話能夠讓程式碼優雅一些,便順手做了個紀錄。

簡單來說,tempfile 是一個 Python 的內建模組,它的工作就是在程式處理資料時,建立一個臨時目錄並將資料實際放置於硬碟上。所以當我們操作這個模組時,它實際上是在硬碟上進行讀寫操作。但有幫助的是,在我們的工作流程結束後,這個臨時目錄就會被自動刪除掉,不用我們額外費心刪除。

這個模組相當適合處理需要臨時儲存卻又不想永久儲存在硬碟上的資料。


使用方法

import tempfile
import os

# Create
with tempfile.TemporaryDirectory() as tmpdirname:
    # And you can save a file under the directory
    tmpfilepath = os.path.join(tmpdirname, "tempfile.txt")
    print(f"Create temporary directory: {tmpdirname}")

    with open(tmpfilepath, 'w') as f:
        f.write("testing")


Output:

Create temporary directory: /tmp/tmpi824kljq/tmpfile.txt


然而,一旦程式結束,你也找不到這個臨時目錄了。


References


Read More

Tags:

Leave a Reply