TransWikia.com

How to iterate through various layers and export each with an additional word to its file name

Geographic Information Systems Asked on July 6, 2021

I’m batch dissolving some layers in QGIS and want to save each dissolved shapefile as <layername>_dissolved.shp. I’m using a for-loop but it just shows raise QgsProcessingException(msg) _core.QgsProcessingException: There were errors executing the algorithm. error.

Here’s my code:

import processing
layers = QgsProject.instance().mapLayers().values()
for i in layers:
    processing.run("native:dissolve", 
                   {'INPUT': i,
                    'OUTPUT': r'C:UsersimperDesktop' + str(i) + '_dissolved' + '.shp'})
    iface.addVectorLayer(str(i+_dissolved), '', 'ogr')

How should I revise my 'OUTPUT' file path?

One Answer

Use double blackslash () or slash(/) to separate directories in the path. Your loop variable "i" is a layer object, not the path to the layer, to get the path to the layer use:

for layer in QgsProject.instance().mapLayers().values():
    layer_path = layer.dataProvider().dataSourceUri().split('|')[0]
    output_path = 'C:UsersimperDesktop' + layer.name() + '_dissolved' + '.shp'
    processing.run("native:dissolve", 
                   {'FIELD': [], 'INPUT': layer_path, 'OUTPUT': output_path})
    iface.addVectorLayer(output_path, layer.name() + '_dissolved', 'ogr')

Correct answer by Zoltan on July 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP