Zuletzt aktiv 9 months ago

tempfile 模組可用於建立臨時檔案或目錄,在程式執行期間存儲暫時資料,並確保在程式結束後自動清理,適用於 測試、快取、臨時儲存 等場景。

temporary_directory_example.py Originalformat
1import tempfile
2import os
3
4with tempfile.TemporaryDirectory() as temp_dir:
5 pid = os.getpid() # 取得當前進程 ID
6 temp_file = os.path.join(temp_dir, f"process_{pid}.txt")
7
8 # 建立並寫入臨時檔案
9 with open(temp_file, "w") as f:
10 f.write(f"這是進程 {pid} 的臨時檔案")
11
12 print(f"臨時目錄: {temp_dir}")
13 print(f"臨時檔案: {temp_file}")
14
15# 離開 `with` 區塊後,臨時目錄和檔案將自動刪除
16
temporary_file_example.py Originalformat
1import tempfile
2
3with tempfile.NamedTemporaryFile(delete=False) as temp_file:
4 print(f"建立的臨時檔案: {temp_file.name}")
5 temp_file.write(b"這是一個具名的臨時檔案。\n")
6
7# `delete=False` 允許我們在 `with` 區塊外存取該檔案
8print("檔案仍然存在,可用於後續操作。")
9
temporary_file_usage.py Originalformat
1import tempfile
2
3with tempfile.TemporaryFile(mode="w+t") as temp_file:
4 temp_file.write("這是一個臨時檔案。\n")
5 temp_file.seek(0) # 重置讀取位置
6 print("讀取臨時檔案內容:", temp_file.read())
7
8# 離開 `with` 區塊後,臨時檔案將自動刪除
9