[gdal-dev] Add to PythonGotchas: saving and closing raster datasets

Mike Toews mwtoews at gmail.com
Sat May 3 21:03:28 PDT 2014


Hi,

This seems to be a common gotcha: http://gis.stackexchange.com/q/93212/1872

I've been caught by it before, and I'm certain many others have too.
This is a gotcha since "WriteArray" doesn't write the array to disk,
but rather it is written when the dataset object is dereferenced. I've
drafted up an entry for the wiki, which could be placed before
"Certain objects contain a Destroy() method, but you should never use
it".

Furthermore, I'm unsure of the best way to demonstrate how to
dereference Python objects. The wiki has two different styles:
    obj = None
or
    del obj

I'm unsure of which is regarded best practice, but encourage
consistency. Please edit as necessary or reply with suggestions.

-Mike


=== Saving and closing datasets ===

To save and close raster datasets, the object needs to be
dereferenced, such as setting it to `None`. It is not written with
{{{WriteArray}}}. For example:
{{{
from osgeo import gdal
driver = gdal.GetDriverByName('GTiff')
dst_ds = driver.Create('new.tif', 10, 15)
band = dst_ds.GetRasterBand(1)
arr = band.ReadAsArray()  # raster values are all zero
arr[2,4:] = 50  # modify some data
band.WriteArray(arr)  # raster file still unmodified
band = None  # dereference band to avoid gotcha described previously
dst_ds = None  # save, close
}}}
The last dereference to the raster dataset writes the data
modifications and closes the raster file. The objects may also be
dereferenced using: {{{del band, dst_ds}}}


More information about the gdal-dev mailing list