close() 方法用於關閉已開啟的檔案物件,釋放系統資源(檔案描述符、緩衝區)。關閉後的檔案不可再讀寫,任何操作將拋出 ValueError: I/O operation on closed file。重複呼叫 close() 安全無副作用。
fileObject.close()
None)。
f = open('foo.txt', 'w')
print("Name:", f.name)
f.write('Hello')
f.close()
print("Closed:", f.closed) # True
# f.write('World') # ValueError
f = open(...))時,舊檔案會自動關閉(參考計數歸零觸發 __del__)。
with open('foo.txt', 'w') as f:
f.write('Hello')
# 區塊結束自動呼叫 f.close(),即使發生例外
class MyFile:
def __init__(self, path, mode):
self.f = open(path, mode)
def __enter__(self):
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close()
return False # 不抑制例外
with MyFile('foo.txt', 'w') as f:
f.write('data')
| 錯誤 | 後果 | 修正 |
|---|---|---|
| 忘記 close() | 資料留在緩衝區未落盤、檔案鎖定、描述符洩漏 | 用 with 區塊 |
| 關閉後繼續操作 | ValueError | 檢查 f.closed 或重構邏輯 |
| 在 finally 中 close() 但未檢查變數存在 | NameError / AttributeError | 用 with 或 try/finally 並初始化 f=None |
close() 是檔案操作的收尾關鍵步驟。現代 Python 開發強制要求使用 with open(...) as f: 模式,以確保資源確定性釋放、資料完整性與程式碼簡潔性。手動呼叫 close() 僅在無法使用 with 的舊版本相容或極特殊流程控制中考慮。