Friday, 31 March 2017

qgis - Merge all shapefiles in a directory - PyQGIS


I'm trying to merge all shapefiles in a directory using the following Python script from the console in QGIS 3.4.


The script was sourced from the following question:



Merging all vector files within directory with QGIS?


gis.stackexchange.com/questions/327398/merging-all-vector-files-within-directory-with-qgis


import glob, os, processing
path_to_shp = "P:/GIS/Basemapping/Topographic Area Schema 1/"
os.chdir(path_to_shp)
filelist = []
for fname in glob.glob("*.shp"):
uri = path_to_shp + fname
filelist.append(uri)


fileliststring = ';'.join(filelist)
processing.run("qgis:mergevectorlayers", fileliststring, "P:/GIS/Basemapping/Topographic Area Schema 1/merged.shp")

Running this results in:


TypeError: QgsProcessingAlgorithm.checkParameterValues(): argument 1 has unexpected type 'str'

The first time I ran into this I checked the input parameters for the algorithm using:


processing.algorithmHelp("qgis:mergevectorlayers")


Based on the algorithmHelp I assumed I should be passing a list of filepaths as input:


list[str]: list of layer sources


Running the following modification of the original script:


import glob, os, processing
path_to_shp = "P:/GIS/Basemapping/Topographic Area Schema 1/"
os.chdir(path_to_shp)
filelist = []
for fname in glob.glob("*.shp"):
uri = path_to_shp + fname
filelist.append(uri)


processing.run("qgis:mergevectorlayers", filelist, "P:/GIS/Basemapping/Topographic Area Schema 1/merged.shp")

results in the following error:


TypeError: QgsProcessingAlgorithm.checkParameterValues(): argument 1 has unexpected type 'list'

I feel I must be missing something obvious here. I've tried passing a list and a string of filepaths but neither seems to work. Can anyone help?



Answer



That's no how you call processing.run. You should check out the official QGIS documentation


Basicaly, processing.run expects the algorithm identifier, and a dictionnary containing the processing parameters. This should work:


processing.run(

"qgis:mergevectorlayers",
{
"LAYERS": filelist,
"OUTPUT": "P:/GIS/Basemapping/Topographic Area Schema 1/merged.shp",
},
)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...