Home »
Python
Python File close() Method with Example
Python File close() Method: Here, we are going to learn about the close() method, how to close an opened file in Python.
By IncludeHelp Last updated : November 26, 2023
File close() Method
The close() method is an inbuilt method in Python, it is used to flush and close the IO object (file). If we close a closed file it has no effect.
Syntax
The syntax of the close() method is:
file_object.close()
Parameter(s)
The following are the parameters of the close() method:
- None - It does not accept any parameter.
Return value
The return type of this method is <class 'NoneType'>, it returns nothing.
close() Method: Example 1
# Python File close() Method with Example
# opening a file in write mode
f = open("Hello.txt", "w")
print("file opened...")
print(f) # prints file details
# closing the file
f.close()
print("file closed...")
Output
file opened...
<_io.TextIOWrapper name='Hello.txt' mode='w' encoding='UTF-8'>
file closed...
close() Method: Example 2
# Python File close() Method with Example
# opening a file in write mode
f = open("Hello.txt", "w")
print("file opened...")
# closing the file
f.close()
# closing a closed file
f.close()
print("file closed...")
Output
file opened...
file closed...