Python proper way to catch exceptions on file close

梦想的初衷 提交于 2021-01-27 09:55:42

问题


I'm old at Perl and new to Python. I know in Perl that fd.close() isn't irrelevant. Writing to a full file system, close() will report the error. Also for socket errors, they appear in close(). So how to do with in Python? Some examples show putting the open() and close() in the same try block which would catch IOError on either. But other examples show close() in the finally block to close the file upon exception. However, what if the exception first occurs in close()?

Does this cover both requirements? (1) Always close the file (2) Catch all IO exceptions?

try:
    with open(FILE, 'w') as fd:
        .....
except IOError as err:
    .....

Thanks, Chris


回答1:


Your code is correct; it can't differentiate errors on open from errors on the (implicit) close when the with block exits (nor differentiate errors from any other file operations in the block), but it will catch all such errors. By the time you reach the except block, you're guaranteed that the file tried to close (the with auto-close will occur before you reach it, whether by fallthrough or an exception being raised), though if the exception occurred during close your options are limited (because recovering meaningfully from close failing is usually not possible).

Note that IOError is not exactly correct; on Py3 it will work as expected (it's an alias of OSError, which is the actual base exception you want to catch), while on Python 2 it's separate from OSError, which means you won't catch OSError or its subclasses (which are commonly seen on Windows systems in particular).

If you want to definitely catch all such errors portably, you want to catch EnvironmentError, which is a superclass of both IOError and OSError on Python 2, and an alias for OSError on Python 3; if portability is not a concern, then OSError is the name that's actually used on Py3, so you may as well use the documented name.




回答2:


Check this answer, one comment says you can open the file separately to find the error on open, then use it as a context manager with try around it again like that:

try:
    f = open( ... )
except IOError:
    ...
try:
    with f:
        ...
except IOError:
    ...


来源:https://stackoverflow.com/questions/53215714/python-proper-way-to-catch-exceptions-on-file-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!