In a couple of my scripts where I need to write a geolocalised raster using the GDAL library in Python, I need to run the script twice to obtain an output. The first run generates the file, but it is empty and comes up with a size of 0 octets on my linux system. It's only when I run the script a second time that the raster gets filled with the information. Why?
I am using anaconda with Python 3.4 and GDAL 2.0.0 and libgdal 2.1.1 (I had many issues finding the right versions for compatibility).
Below a working example that causes the issue for me:
import numpy as np from osgeo import gdal, osr # Create a random 100x100 raster test_dem = np.random.rand(100,100) # Get size of raster DEM_size = np.shape(test_dem) # Output file path dstfile = '/output/file.tiff' # Make geotransform xmin,ymax = [296058.21,4990799.17] nrows,ncols = DEM_size xres = 1 yres = 1 geotransform = (xmin,xres,0,ymax,0, -yres) # Write output driver = gdal.GetDriverByName('Gtiff') dataset = driver.Create(dstfile, ncols, nrows, 1, gdal.GDT_Float32) dataset.SetGeoTransform(geotransform) srs = osr.SpatialReference() srs.ImportFromEPSG(32632) dataset.SetProjection(srs.ExportToWkt()) dataset.GetRasterBand(1).WriteArray(test_dem)