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模块方法