[GIS] Merging multiple TIFF files into one TIFF file with multiple bands using Python

gdalpythonrasterio

I am trying to merge multiple TIFF files into one multi-band TIFF using Python.
I used subprocess.checkoutput('python gdal.merge.py') and it was working well.
But I am looking for another way to do this without using any external process.
Is there a library or a way that I can use.
This is the code I used

basename = '*'
outdir2 = './TIFF_Files'
filelist2 = glob.glob(os.path.join(outdir2, basename))
files_string = " ".join(filelist2)
print(files_string)
Tiff_output = os.path.join(outdir2,'Multi_band.tif')
command = "python gdal_merge.py -o " + Tiff_output + " -of gtiff -separate " + files_string
output = subprocess.check_output(command)

Keep in mind that I am not really advanced in Python.

Best Answer

I think you can do this with the GDAL bindings directly, by first building an in-memory VRT (virtual file), and then dumping that to disk. The VRT can take loads of other options too in order to create the mosaic.

from osgeo import gdal
# Assume filelist2 is as above
# Build an in-memory VRT
gg = gdal.BuildVRT("", filelist2, separate=True)
g = gdal.Translate("Multi_band.tif", gg, fmt="GTiff") 
# or fmt="COG" if you want Cloud Optimised GeoTIFF and you have 
# a recent GDAL build.