Exercise 1.11: PermissionError returned on top of ZeroDivisionError on Windows system
When executing the solution for exercise 1.11, I got a cryptic PermissionError
on top of the ZeroDivisionError
when trying to write (or actually delete) the I_should_be_deleted.csv
file.
Interestingly, this only happened on my Windows system (via a jupyter notebook) but not on my ubuntu WSL.
(Also, everything worked fine for the I_should_exist.csv
example.)
This might not be very relevant since most people are working with Linux or Mac anyway, but I thought I'd share it regardless :)
import os
from contextlib import contextmanager
@contextmanager
def safe_write(filename):
with open(filename, 'wt') as fh:
try:
yield fh
except ZeroDivisionError:
os.remove(filename)
# re-raising the ZeroDivisionError exception ensures we don't silence the error
# try omitting the next line and compare the resulting behavior
raise
with safe_write("I_should_be_deleted.csv") as out:
value = 500 / 0
out.write(f"{value}\n")
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-17-92cfcbd004dc> in safe_write(filename)
8 try:
----> 9 yield fh
10 except ZeroDivisionError:
<ipython-input-18-c487a4dd208f> in <module>
1 with safe_write("I_should_be_deleted.csv") as out:
----> 2 value = 500 / 0
3 out.write(f"{value}\n")
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
PermissionError Traceback (most recent call last)
<ipython-input-18-c487a4dd208f> in <module>
1 with safe_write("I_should_be_deleted.csv") as out:
2 value = 500 / 0
----> 3 out.write(f"{value}\n")
~\anaconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
128 value = type()
129 try:
--> 130 self.gen.throw(type, value, traceback)
131 except StopIteration as exc:
132 # Suppress StopIteration *unless* it's the same exception that
<ipython-input-17-92cfcbd004dc> in safe_write(filename)
9 yield fh
10 except ZeroDivisionError:
---> 11 os.remove(filename)
12 # re-raising the ZeroDivisionError exception ensures we don't silence the error
13 # try omitting the next line and compare the resulting behavior
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'I_should_be_deleted.csv'