In this python file program, we will check whether a file is closed or not with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.
#readcontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.
Line5 : This is Africa.
Line6 : This is Korea.
Line7 : This is Germany.
Line8 : This is China.
Steps to solve the program
- Open the file by using open(“readcontent.txt”,”r”).
- Print file.closed, it will print True if the file is closed and False if not.
- Now close the file.
- Again use file.closed to check whether the file is closed or not.
# Open file in read mode
f = open('readcontent.txt','r')
# Check whether the file is closed or not
print(f.closed)
# Close the file
f.close()
# Check whether the file is closed or not
print(f.closed)
Output :
False True