Changes between Version 16 and Version 17 of PythonGotchas


Ignore:
Timestamp:
Oct 1, 2014, 7:28:17 PM (10 years ago)
Author:
Mike Taves
Comment:

gotcha for saving and closing GDAL datasets / OGR datasources

Legend:

Unmodified
Added
Removed
Modified
  • PythonGotchas

    v16 v17  
    171171shouldn't call Destroy() at all.
    172172}}}
     173
     174
     175=== Saving and closing datasets/datasources ===
     176
     177To save and close GDAL raster datasets or OGR vector datasources, the object needs to be dereferenced, such as setting it to {{{None}}}, a different value, or deleting the object. If there are more than one copies of the dataset or datasource object, then each copy needs to be dereferenced.
     178
     179For example, creating and saving a raster dataset:
     180{{{
     181#!python
     182>>> from osgeo import gdal
     183>>> driver = gdal.GetDriverByName('GTiff')
     184>>> dst_ds = driver.Create('new.tif', 10, 15)
     185>>> band = dst_ds.GetRasterBand(1)
     186>>> arr = band.ReadAsArray()  # raster values are all zero
     187>>> arr[2, 4:] = 50  # modify some data
     188>>> band.WriteArray(arr)  # raster file still unmodified
     189>>> band = None  # dereference band to avoid gotcha described previously
     190>>> dst_ds = None  # save, close
     191}}}
     192The last dereference to the raster dataset writes the data modifications and closes the raster file. {{{WriteArray(arr)}}} does not write the array to disk, unless the GDAL block cache is full (typically 40 MB).
     193
     194With some drivers, raster datasets can be intermittently saved without closing using {{{FlushCache()}}}. Similarly, vector datasets can be saved using {{{SyncToDisk()}}}. However, neither of these methods guarantee that the data are written to disk, so the preferred method is to deallocate as shown above.
     195
    173196
    174197=== Exceptions raised in custom error handlers do not get caught ===