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)
srs = osr.SpatialReference()                
  • writes for me on the first run, I modified the last line to: dataset.GetRasterBand(1).WriteArray(test_dem) I'm using OSGeo on windows though
    – user92055
    Sep 21 '17 at 14:16
  • I edited the last line: it was a typo. If it works on Windows, it's not the code: I wonder if it comes from the Anaconda setup, as I had to downgrade some libraries to get gdal to work. I'm surprised about the downvotes: for this question I don't see why this isn't clear or useful!
    – Maxim L
    Sep 21 '17 at 15:07
  • 1
    I think you may need to close the file for it to write. Try adding "dataset=None" at the end of the code.
    – Jon
    Sep 21 '17 at 16:27
  • Yes! Thanks. Could you please add your comment as an answer so I can select it?
    – Maxim L
    Sep 21 '17 at 16:49

GDAL requires that you close the dataset in order to write to disk. Try adding

dataset = None

to the end of your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.