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)
-
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 thoughuser92055– user920552017年09月21日 14:16:39 +00:00Commented 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!Maxim L– Maxim L2017年09月21日 15:07:37 +00:00Commented Sep 21, 2017 at 15:07
-
1I think you may need to close the file for it to write. Try adding "dataset=None" at the end of the code.Jon– Jon2017年09月21日 16:27:34 +00:00Commented Sep 21, 2017 at 16:27
-
Yes! Thanks. Could you please add your comment as an answer so I can select it?Maxim L– Maxim L2017年09月21日 16:49:55 +00:00Commented Sep 21, 2017 at 16:49
1 Answer 1
GDAL requires that you close the dataset in order to write to disk. Try adding
dataset = None
to the end of your code.