I have a raster image and would like to open it with gdal to pull some information about the projection.
Opening with the following code works fine:
from osgeo import gdal
gtiff = gdal.Open(filename)
prj = gtiff.GetProjection()
# do some work
However, the following doesn't work:
with gdal.Open(filename) as gtiff:
prj = gtiff.GetProjection()
Instead an attribute error is displayed:
AttributeError: __exit__
I thought the latter is commonly accepted as better style. I'm using Python 3.4.5 :: Continuum Analytics, Inc. (anaconda).
Python relies on "magic methods" for many of its paradigms. The call to len(x)
, for instance, calls x.__len__()
. Equalities like >
or >=
also use magic methods that are double-underscored.
The with X as x
paradigm of Python relies on two magic methods: X.__enter__
and X.__exit__
. The class returned by gdal.Open
is a gdal.Dataset
, which does not have these methods. It therefore throws an error when using a with as
statement like you provided.
The proper way to open and close a gdal.Dataset
is:
import gdal
ds = gdal.Open('filename.tif', gdal.GA_Update)
# do something
del ds
Deleting the Dataset
will ensure that changes were written to the file. You can also write those changes by running ds.FlushCache()