🐍 When you open a file, you are required to close it too. If between your open statement and close statement there are n other statements, and in any of the statement an error occurs, your program won't reach the point to close the file. It will remian opened. Try this to understand the issue.
Input
f = open('some_file.txt', 'a')
f.readlines()
f.close()
Output
UnsupportedOperation Error
Input
f.write('add more text to test if file is open')
Output
37
The above example shows that at line 2 an error occurred and the program didn't reach line 3 to close the file. Later we wrote something to the file and it worked, which means the file is still open. Run the close statement again to close it.
Input
f.close()
Protect the file with try/except/finally
One solution to this is use of try/except/finally statements as follows.
Input
f.open('some_file.txt', 'a')
try:
f.readlines()
except:
print('An exception was raised.')
finally:
f.close()
Output
An exception was raised.
Here even if an error occurs, finally statement will be run and that will close the file. You can test that the file is closed by trying to write something in it.
Input
f.write('add more text to test if file is open')
Output
ValueError Error
With Statement
Try/except/finally is great. But too lengthy. One can do the same in short with WITH statement.
Input
with open('oops.txt','a') as f:
f.readlines()
Output
UnsupportedOperation Error
The error has occurred in line 2. Now let's test if the file is still open.
Input
f.write('add more text to test if file is open')
Output
ValueError Error
Excellent. ValueError means the file is closed and write operation is not working because of it. It automatically closes the file on encountering an error.
Comments
Post a Comment