Python provides different methods for file operations. After the file operation completed the file should be closed with the close() method properly. when the close method is executed the given file will be closed and can not be read or write anymore. In this tutorial, we will learn how to close the file with the Python close() method.
close() Method Syntax
close() method is provided via the opened file object. close() method has very simple syntax where it doesn't have any parameter. When it is called it will close its file object and do not return any value.
- FILEOBJECT is the file which is all ready opened previously.
Lets make a simple example where we will open and close a file.
#Open the file named test.txt f = open("test.txt","w") #Close the file named test.txt f.close()
Close Read Only File
Some files can be opened for only read. There is not need to write new data into these files. These files are called as
Read-Only . We can also use the close() method in order to close the read-only files which is the same like closing other files.
#Open the file named test.txt read-only f = open("test.txt","r") #Close the file named test.txt f.close()
Check If Given File Is Closed
Before trying to close, read, or write checking a file if it is closed is a good habit. The file object provides the
closed attribute which returns the status of the file. If the file is closed the
closed attribute will return true and if the file is opened closed attribute will return false. We can use the closed attribute with the close() method like below. We will check if the file is still open and close the file if it is already opened.
#Open the file named test.txt read-only f = open("test.txt","r") if not f.closed: #Close the file named test.txt f.close() else: print("File all ready closed")