Python檔close()方法

close()方法關閉打開的檔。調用此方法後將無法讀取或寫入封閉檔。任何需要打開該檔的操作將在檔關閉後引發ValueError。允許多次調用close()

當檔的引用對象重新分配給另一個檔時,Python會自動關閉一個檔。 使用close()方法關閉檔是個好習慣。

語法

以下是close()方法的語法 -

fileObject.close()

參數

  • NA

返回值

  • 此方法不返回任何值。

示例

以下示例顯示了close()方法的用法。

#!/usr/bin/python3

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

# Close opened file
fo.close()

執行上面代碼後,將得到以下結果 -

Name of the file:  foo.txt

上一篇: Python檔對象方法 下一篇: Python os模組方法