Python - File close() Method
The Python file close() method is used to close the specified file. Please note that, file must has opened before using the method.
Syntax
file.close()
Parameters
No parameter is required.
Return Value
None.
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 print(MyFile.read()) MyFile.close() #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 print(MyFile.read())
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