萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 檔案操作 close() 方法:關閉檔案、釋放資源、Context Manager 最佳實踐

方法簽名

file.close() -> None

行為

  • 刷新寫入緩衝區至磁碟。
  • 釋放作業系統檔案描述符。
  • 關閉後再呼叫 read/write/seek 會拋出 ValueError: I/O operation on closed file.。
  • 重複呼叫 close() 安全無副作用。

範例

f = open("foo.txt", "w")
f.write("data")
f.close()
print(f.closed)  # True
# f.write("more")  # ValueError

為什麼要用 with 區塊?

# 手動管理 (不推薦)
f = open("data.txt", "w")
try:
    f.write("critical")
finally:
    f.close()  # 即使發生例外也會執行

# with 區塊 (推薦,等價上述 try/finally)
with open("data.txt", "w") as f:
    f.write("critical")
# 這裡自動 f.close()

with 區塊優勢

  1. 例外安全:任何例外離開區塊都會呼叫 __exit__ → close()。
  2. 可讀性:明確界定檔案生命週期範圍。
  3. 巢狀支援:多檔案同時開啟:
with open("a.txt") as fa, open("b.txt", "w") as fb:
    fb.write(fa.read())

特殊情況:不想用 with

  • 檔案需跨函式/物件生命週期共享 → 手動管理並建立明確的 close() 責任鏈。
  • 互動式 REPL 探索時可暫不關閉,但养成習慣用 with。

底層細節

  • CPython 參考計數機制:變數離開作用域 → refcount=0 → __del__ → close(),但不保證時機(PyPy、循環參考會延遲)。
  • os.fdopen(fd) 包裝的檔案物件,close() 只關閉包裝層,底層 fd 需另行管理。
copyright © 萬盛學電腦網 all rights reserved