Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries

The Python file close() method is used to close the specified file. Please note that, file must has opened before using the method.




No parameter is required.

Return Value


Example: Close an opened file in Python

In the below example, Python file close() method is used to close an opened file called MyFile. The file read() method returns the content of the file if it is used before closing the file, else an exception is raised.

MyFile = open("python_test.txt", "r")

#read content before closing the file

#Assuming the file contains
#This is line 1 content.
#This is line 2 content.
#This is line 3 content.
#This is line 4 content.
#This is line 5 content.

#read content after closing the file

The output of the above code will be:

This is line 1 content.
This is line 2 content.
This is line 3 content.
This is line 4 content.
This is line 5 content.

ValueError: I/O operation on closed file.

❮ Python File Handling Methods