Search code examples
pythonexceptioncontextmanager

How should I catch exceptions raised by `with open(filename)` in Python?


The act of attempting to open a file in Python can throw an exception. If I'm opening the file using the with statement, can I catch exceptions thrown by the open call and the related __enter__ call without catching exceptions raised by the code within the with block?

try:
    with open("some_file.txt") as infile:
        print("Pretend I have a bunch of lines here and don't want the `except` below to apply to them")
        # ...a bunch more lines of code here...
except IOError as ioe:
    print("Error opening the file:", ioe)
    # ...do something smart here...

This question is different from this older one in that the older one is about writing a context manager, rather than using the familiar with open.


Solution

  • can I catch exceptions thrown by the open call and the related __enter__ call without catching exceptions raised by the code within the with block?

    Yes:

    #!/usr/bin/env python3
    import contextlib
    
    stack = contextlib.ExitStack()
    try:
        file = stack.enter_context(open('filename'))
    except OSError as e:
        print('open() or file.__enter__() failed', e)
    else:
        with stack:
            print('put your with-block here')
    

    with the default open() function, __enter__() shouldn't raise any interesting exceptions and therefore the code could be simplified:

    #!/usr/bin/env python    
    try:
        file = open('filename')
    except OSError as e:
        print('open() failed', e)
    else:
        with file:
            print('put your with-block here')