首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 檔案操作:close() 方法關閉檔案完整教學

     編輯:更多程式設計知識

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__)。
  • 程式正常結束時,所有檔案自動關閉。
  • 不建議依賴自動關閉,資源釋放時機不確定,可能導致資料遺失(緩衝區未 flush)或檔案鎖定過久。

最佳實踐:with 區塊(Context Manager)


with open('foo.txt', 'w') as f:
    f.write('Hello')
# 區塊結束自動呼叫 f.close(),即使發生例外
  • 簡潔、安全、可讀性高。
  • 適用於所有支援 context manager 協議的物件(檔案、socket、鎖、資料庫連線等)。

進階:自訂類別支援 with


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 的舊版本相容或極特殊流程控制中考慮。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved