Clip Multiple Layers in QGIS with PyQGIS - Tutorial

ClipMultipleLayersPyQGIS.PNG

Interesting tutorial to clip multiple polygon layers in QGIS with the Python console. The tutorial also shows a code to upload all files from a directory and store them as objects in a Python dictionary.

 

Tutorial

 

Code

This is the complete Python code for the tutorial:

import os

mainLayerFolder = 'C:\Users\Saul\Documents\Ih_AnalisisdeAreasNoSuperpuestasporMultiplesCapasconQGISyPyQGIS\Shp'

listFilterShapes = []
for item in os.listdir(mainLayerFolder + '/CapasFiltro/'):
    if item[-3:]=='shp':
        listFilterShapes.append(item)

print(listFilterShapes)

dictFilterShapes = {}

for shape in listFilterShapes:
    dictFilterShapes[shape[:-4]] = iface.addVectorLayer(mainLayerFolder + '/CapasFiltro/' + shape,shape[:-4],"ogr")
    
areaOfInterest = iface.addVectorLayer(mainLayerFolder + '/AreadeInteres/AreadeInteres_Extended.shp' ,'AreadeInteres_Extended',"ogr")

from processing.tools import *

for layer in dictFilterShapes.keys():
    general.runalg("qgis:clip",\
                        dictFilterShapes[layer],\
                        areaOfInterest,\
                        mainLayerFolder + '/OutputShp/'+layer+'_Clip.shp')
    iface.addVectorLayer(mainLayerFolder + '/OutputShp/'+layer+'_Clip.shp',layer+'_Clip',"ogr")

 

Input files

You can download the input files in this link.

Saul Montoya

Saul Montoya es Ingeniero Civil graduado de la Pontificia Universidad Católica del Perú en Lima con estudios de postgrado en Manejo e Ingeniería de Recursos Hídricos (Programa WAREM) de la Universidad de Stuttgart con mención en Ingeniería de Aguas Subterráneas y Hidroinformática.

Smiley face

Subscribe to our free e-newsletter for tutorials, articles, webminars, courses and more.