Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

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.




No parameter is required.

Return Value


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")

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ Python File Handling Methods