Python 檔案 close() 方法



Python 檔案close()方法關閉當前開啟的檔案。眾所周知,如果開啟檔案以對其執行任務,則在完成任務後必須關閉它。這樣做是為了確保作業系統上開啟的檔案數量不超過其設定的限制。

在作業系統中關閉檔案是必要的,因為保留太多開啟的檔案容易受到漏洞的影響,並可能導致資料丟失。因此,除了此方法之外,當檔案的引用物件重新分配給另一個檔案時,Python 會自動關閉檔案。但是,仍然建議使用 close() 方法以正確的方式關閉檔案。

關閉檔案後,就無法再讀取或寫入檔案。如果對已關閉的檔案執行操作,則會引發 ValueError,因為該檔案必須處於開啟狀態才能執行該操作。

注意:此方法可以在程式中多次呼叫。

語法

以下是 Python close()方法的語法:

fileObject.close()

引數

該方法不接受任何引數。

返回值

此方法不返回值。

示例

以下示例顯示了 Python close() 方法的使用方法。首先,我們使用檔案物件“fo”以寫入二進位制 (wb) 模式開啟一個檔案。然後,在使用 close() 方法關閉檔案之前,我們顯示檔名。

# Open a file using a file object 'fo'
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)

# Close the opened file
fo.close()

當我們執行以上程式時,它會產生以下結果:

Name of the file:  foo.txt

示例

關閉檔案後,我們無法對檔案執行任何操作。這將引發 ValueError。

這裡,一個測試檔案“foo.txt”使用檔案物件以寫入模式 (w) 開啟。然後,使用 close() 方法,我們在嘗試對其執行寫入操作之前關閉此檔案。

# Open a file using a file object 'fo'
fo = open("foo.txt", "w")

# Close the opened file
fo.close()

# Perform an operation after closing the file
fo.write("Hello")

讓我們編譯並執行給定的程式,以產生以下輸出:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
fo.write("Hello")
ValueError: I/O operation on closed file.

示例

close() 方法可以在單個程式中多次呼叫。

在以下示例中,我們以寫入 (w) 模式開啟名為“test.txt”的檔案。然後,在兩次呼叫 close() 方法之前,對檔案執行寫入操作。

# Open a file using a file object 'fo'
fo = open("test.txt", "w")

# Perform an operation after closing the file
fo.write("Hello")

# Close the opened file
fo.close()
fo.close()

執行上述程式後,使用 write() 方法寫入的字串將反映在 test.txt 檔案中,如下所示。

Hello
python_file_methods.htm
廣告