[GIS] GDAL Translate error

gdalpythonxyz

I am trying to translate a .tif raster to an xyz one in Python

The code is this:

import sys
from osgeo import gdal


gdal.AllRegister()
driver = gdal.GetDriverByName('Local Disk')

dataset = gdal.Open('C:\Delft3D\Teste\GDAL\clc_raster.tif')

if dataset is None:
    print "Could not!"
    sys.exit(1)

gdal_translate -of XYZ dataset.tif C:\Delft3D\Teste\GDAL\clc_raster.tif.xyz

dataset = None

But I get the following error.

   gdal_translate -of XYZ dataset.tif C:\Delft3D\Teste\GDAL\clc_raster2.xyz
                        ^
   SyntaxError: invalid syntax

I don't know why this error appears. I used the tips from convert geotiff to simple xyz elevation file?

Best Answer

You are trying to execute a command line utility from within Python. To do this you can use subprocess, which takes the command line arguments as a list of strings.

import subprocess    
cmd = ["gdal_translate", "-of", "XYZ", "dataset.tif", r"D:\Delft3D\Teste\GDAL\clc_raster.tif.xyz"]
subprocess.call(cmd)

edit:

Additionally I'd like to point out that a lot of your code is superfluous if you use subprocess or os.system to execute a command line utility.

This is all you need:

import subrocess

in_file = r"D:\input\dataset.tif"
out_file = r"D:\output\dataset.xyz"

cmd = ["gdal_translate",
       "-of", "XYZ",
       in_file,
       out_file]
subprocess.call(cmd)
Related Question