from contextlib import contextmanager @contextmanager def open_file(file_path, mode): file = open(file_path, mode) try: yield file # 提供檔案資源 finally: file.close() # 確保檔案關閉 print(f"檔案 {file_path} 已關閉") # 使用自訂上下文管理器 with open_file("example.txt", "w") as f: f.write("這是一個測試檔案\n")