I am new to python and breaking my head on how to use gdal_merge in a (spyder) python script. I use Windows 10, Python 3.6 and have the gdal tool installed from osgeo4w. I realize many other posts describe this problem but none could help me resolving this issue.

When i call the gdal module from cmd, it works like a charm:

 python "C:\OSGeo4W64\bin\gdal_merge.py" -o merged.tif input1.tif input2.tif

However, I cannot get it working properly in a python script (spyder).

A first approach produces an output but not with the right name: it produces an 'out.tif' file and not the 'merged.tif' file as I request:

import sys
import gdal_merge as gm
gm.main(['-o', 'merged.tif', 'N00W078.tif', 'N00W079.tif'])

A second approach simply produces no output:

import subprocess
merge_command = ["python", "C:\OSGeo4W64\bin\gdal_merge.py", "-o", "merged.tif", "input1.tif", "input2.tif"]

Any thoughts on how to resolve this issue?

2 Answers 2


Add an empty argument in the first approach (because gdal_merge.py parses arguments starting from 1 and not 0):

import sys
import gdal_merge as gm
gm.main(['', '-o', 'merged.tif', 'N00W078.tif', 'N00W079.tif'])

Join the path of gdal_merge.py in the second approach:

import os, subprocess
gm = os.path.join('C:\\','OSGeo4W64','bin','gdal_merge.py')
merge_command = ["python", gm, "-o", "merged.tif", "input1.tif", "input2.tif"]

Windows 10, Python 3.9, QGIS 3.20 (installed with OSGeo4W). This code works fine:

import osgeo_utils.gdal_merge
output_file_path = r'insert path here'
input_files_path = r'insert path here'
parameters = ['', '-o', output_file_path] + input_files_path + ['-separate', '-co', 'COMPRESS=LZW']

the -separate flag puts each input in a different band in the raster, if you need the normal merge where the output raster has one band don't use it

parameters = ['', '-o', output_file_path] + input_files_path + ['-co', 'COMPRESS=LZW']

Your Answer

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

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