Python close method:
The close is a method of IOBase class in Python that flush and close the current stream. However, this method has no effect if the file is already closed. After closing a file, any read or write operation will raise a ValueError exception.
Method Signature
The signature for the close method is as shown below.
fileObject.close()
Method parameters and return type
- Here, the close method doesn’t take any parameters.
- However, it doesn’t return any value.
Python close() Examples:
Example 1: In this example, we will open a file in reading mode and close it when a read operation is done.
# Open a file
f1 = open("test.txt", "r")
print ("File Name ", f1.name)
print(f1.read())
# Closing file
f1.close()
Output
File Name test.txt
Hello, everyone
Welcome to the world of Python Programming.
Example 2: In this example, we will open a file in write mode and try to read the content after writing. This will not read data we have written due to buffering.
# Open a file
f1 = open("test1.txt", "w+")
print ("File Name ", f1.name)
#Writing to a file
f1.write("Hello Python")
#Trying to read
print(f1.read())
#Closing
fd1 = f1.close()
Output
File Name test.txt
Example 3: In this example, we will write to a file and close it. Thereafter, we will open the same file for reading.
#Initializing
# Open a file
f1 = open("test1.txt", "w")
print ("File Name ", f1.name)
#Writing to a file
f1.write("Hello Python")
#Closing a file
fd1 = f1.close()
#Opening again in read mode
f1 = open("test1.txt", "r")
print(f1.read())
#Closing a file
fd1 = f1.close()
Output
File Name test.txt
Hello Python
Conclusion
Hence, the close() method flushes and closes the stream.
References
Happy Learning 🙂