I've started learning pyQGIS and the first step was to work on easy things like to add raster and vector in QGIS. So, I found this code in Loading raster layer using PyQGIS? and it works fine and is easy.
from qgis.core import QgsRasterLayer from PyQt4.QtCore import QFileInfo def StringToRaster(raster): # Check if string is provided fileInfo = QFileInfo(raster) path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsMapLayerRegistry.instance().addMapLayer(layer) if layer.isValid() is True: print "Layer was loaded successfully!" else: print "Unable to read basename and file path - Your string is probably invalid" raster = 'C:/home/user/Desktop/output.tif' StringToRaster(raster)
However, I have some question : this code works with one absolute path to one raster but, if it exists a list of paths like this:
raster = ['C:/home/user/Desktop/output.tif','C:/home/user/Desktop/output2.tif','C:/home/user/Desktop/output3.tif','C:/home/user/Desktop/output4.tif']
How to make this code works such it adds all the rasters in the list?