1

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?

jessie jes
  • 1,061
  • 8
  • 21
  • This question is about basic Python. You can consult this wiki: https://wiki.python.org/moin/ForLoop – xunilk Mar 22 '17 at 19:37

1 Answers1

1

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:
    StringToRaster(rasterName)
nash
  • 1,976
  • 14
  • 19