open() and EOFError

Marko Rauhamaa marko at pacujo.net
Mon Jul 7 13:31:53 EDT 2014


Ian Kelly <ian.g.kelly at gmail.com>:

> It's good practice to keep your try blocks as narrow as possible in
> any case.

True. Unfortunately, that leads to trouble with the handy "with"
construct:

    with open(path) as f:
        ...

If the open() call is guarded against exceptions (as it usually should),
one must revert to the classic syntax:

    try:
         f = open(path)
    except IOError:
         ...
    try:
         ...
    finally:
         f.close()


Marko



More information about the Python-list mailing list