Zuletzt aktiv 9 months ago

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

timmy hat die Gist bearbeitet 9 months ago. Zu Änderung gehen

3 files changed, 31 insertions

temporary_directory_example.py(Datei erstellt)

@@ -0,0 +1,15 @@
1 + import tempfile
2 + import os
3 +
4 + with 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` 區塊後,臨時目錄和檔案將自動刪除

temporary_file_example.py(Datei erstellt)

@@ -0,0 +1,8 @@
1 + import tempfile
2 +
3 + with tempfile.NamedTemporaryFile(delete=False) as temp_file:
4 + print(f"建立的臨時檔案: {temp_file.name}")
5 + temp_file.write(b"這是一個具名的臨時檔案。\n")
6 +
7 + # `delete=False` 允許我們在 `with` 區塊外存取該檔案
8 + print("檔案仍然存在,可用於後續操作。")

temporary_file_usage.py(Datei erstellt)

@@ -0,0 +1,8 @@
1 + import tempfile
2 +
3 + with 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` 區塊後,臨時檔案將自動刪除
Neuer Älter