2

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?

2 Answers 2

4

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)
2
  • The process runs, but it doesn't create the file. I guess it's something wrong with the command line arguments.
    – Litwos
    Jan 25, 2016 at 10:43
  • It should create file at D:\Delft3D\Teste\GDAL\clc_raster.tif.xyz as long as you execute the Python script in the same directory as dataset.tif and the directory `D:\Delft3D\Teste\GDAL` already exists.
    – Kersten
    Jan 25, 2016 at 11:43
3

You could use another option like:

os.system("gdal_translate -of XYZ " + source_file + " " +  out_file)
0

Your Answer

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

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