Search code examples
pythonfilegeospatialogr

Use Python "with" statement for ogr.open(file)


Is it possible to use the Python "with" statement with the ogr.open(file) function?

For example, I would like to do something like:

with ogr.open(file) as ds:

At the moment, I can only get the following to work:

try:
    ds = ogr.open(file)
    ...

except:
    del ds

Solution

  • According to the documentation, it appears that you cannot use with ogr.Open(file) ...

    A Python object that you use in a with statement needs to have methods __enter__ and __exit__ to set up and take down a context used inside the with block. Here's an explanation.

    According to the Documentation for OGR Open, these __enter__ and __exit__ methods are not defined for the DataSource object returned by Open so you cannot use the result from ogr.Open as the subject of a with statement.

    So it looks like you'll have to use your try/except combination (although a try/finally combination might be better).