Skip to main content

close()

The close() function in Python is a method used to close an open file. This operation frees up system resources that were being used by the file. It is essential to close files after reading from or writing to them to ensure that no data is lost or corrupted. Failure to close files properly can lead to memory leaks and other issues.

Parameter Values

This function does not accept any parameters.

Return Values

The close() method from File Methods returns None.

How to Use close() in Python

Example 1:

The close() method closes the file. A closed file cannot read, write, or interact with its contents anymore.

file = open('example.txt', 'r')
file.close()
print(file.closed) # Output: True
Example 2:

It is a good practice to always close a file after performing operations on it to free up system resources.

file = open('data.csv', 'w')
# Perform operations on the file
file.close()
Example 3:

If a file is not closed explicitly using close(), Python's garbage collector eventually closes it, but it is recommended to do so explicitly.

file = open('image.png', 'rb')
# Perform operations on the file
file.close()