3

I've been trying to automate the merge vector layers via PyQGIS but I can't seem to get it right. This is my code:

import os
import processing 

loc = r"C:\Users\loc"
os.chdir(loc)

shapelist = os.listdir(os.getcwd())

for file in shapelist:
    if "R4A.shp" in file:
        R4A = print(file)

Parameter1 = "QgsProcessingParameterMultipleLayers"
Parameter2 = "QgsProcessingParameterCrs"
Parameter3 = "QgsProcessingParameterFeatureSink"

#parameters = "Parameter1: file1.shp; file2.shp; file3.shp; file4.shp, Parameter2: 'EPSG:4326', Parameter3: r"C:\Users\destination"

processing.run("qgis:mergevectorlayers", parameters) 

I always get this error: SyntaxError: invalid syntax

2

The parameters should be in dictionary format with the key being the name of the algorithm parameter and the value being the value. You can set the input layers to be stored in a list when you iterate through your directory, this should make it easier instead of typing each shapefile individually.

So you could use something like the following:

import os
import processing 

loc = r"C:\Users\loc"
os.chdir(loc)
files = os.listdir(os.getcwd())

shapefile_list = []
for file in files:
    if "R4A.shp" in file:
        print(file)
        shapefile_list.append(file)

parameters = {'LAYERS': shapefile_list, 
              'CRS': 'EPSG:4326', 
              'OUTPUT': r"C:\Users\destination\result.shp"}

processing.run("qgis:mergevectorlayers", parameters) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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