Python - File close() Method
The Python 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
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, the file called test.txt is opened to read the content of the file. After that the file stream is closed using close() method.
Please note that performing operation like read, write or append on a closed file raises exception.
#file is opened in read mode MyFile = open("test.txt", "r") print(MyFile.read()) MyFile.close()
The output of the above code will be:
This is a test file. It contains dummy content.
❮ Python File Handling Methods