Using "with" context handler, and catching specific exception?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Oct 21 22:48:17 EDT 2013


On Mon, 21 Oct 2013 18:43:39 -0700, Victor Hooi wrote:

>     try:
>         with open('somefile.log', 'wb' as f:
>             f.write("hello there")
>     except IOError as e:
>         logger.error("Uhoh, the file wasn't there").

I hope that this isn't what you are actually doing. IOError is not just 
for "File Not Found".


py> open("/home")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 21] Is a directory: '/home'

py> open("/root/foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: '/root/foo'


-- 
Steven



More information about the Python-list mailing list