import tempfile import os with tempfile.TemporaryDirectory() as temp_dir: pid = os.getpid() # 取得當前進程 ID temp_file = os.path.join(temp_dir, f"process_{pid}.txt") # 建立並寫入臨時檔案 with open(temp_file, "w") as f: f.write(f"這是進程 {pid} 的臨時檔案") print(f"臨時目錄: {temp_dir}") print(f"臨時檔案: {temp_file}") # 離開 `with` 區塊後,臨時目錄和檔案將自動刪除