4

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)
PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Sep 21, 2017 at 13:59
4
  • 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 Commented Sep 21, 2017 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! Commented Sep 21, 2017 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. Commented Sep 21, 2017 at 16:27
  • Yes! Thanks. Could you please add your comment as an answer so I can select it? Commented Sep 21, 2017 at 16:49

1 Answer 1

8

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

dataset = None

to the end of your code.

answered Sep 21, 2017 at 17:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.