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)

    if layer.isValid() is True:
        print "Layer was loaded successfully!"

        print "Unable to read basename and file path - Your string is probably invalid"

raster = 'C:/home/user/Desktop/output.tif'

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?

closed as off-topic by PolyGeo Mar 24 '17 at 9:46

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.


A simple 'for' loop should help you achieve what you are trying to do.

Try replacing the last two lines with -

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']
for rasterName in raster:

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