Python File close()方法教程

Python为文件操作提供了不同的方法。文件操作完成后,应使用close()方法正确关闭文件。当close方法被执行时,给定的文件将被关闭,并且不能再读取或写入。在本教程中,我们将学习如何使用Python close()方法关闭文件。

null

close()方法语法

这个 close() 方法是通过打开的文件对象提供的。close()方法的语法非常简单,没有任何参数。当调用它时,它将关闭其文件对象,并且不返回任何值。

FILEOBJECT.close()
  • FILEOBJECT是以前打开的文件。

关闭文件

让我们做一个简单的例子,我们将打开和关闭一个文件。

#Open the file named test.txtf = open("test.txt","w")#Close the file named test.txtf.close()

关闭只读文件

有些文件只能以只读方式打开。不需要将新数据写入这些文件。这些文件称为 Read-Only . 我们还可以使用close()方法来关闭只读文件,这与关闭其他文件一样。

#Open the file named test.txt  read-onlyf = open("test.txt","r")#Close the file named test.txtf.close()

检查给定文件是否已关闭

在尝试关闭、读取或写入文件之前,检查文件是否已关闭是一个好习惯。file对象提供 closed 返回文件状态的属性。如果文件已关闭 closed 属性将返回true,如果打开文件,则关闭属性将返回false。我们可以将close属性与close()方法一起使用,如下所示。我们将检查文件是否仍处于打开状态,如果已打开,则关闭文件。

#Open the file named test.txt  read-onlyf = open("test.txt","r")if not f.closed:   #Close the file named test.txt   f.close()else:   print("File all ready closed")
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享