3

I am unsuccessfully trying to merge all shapefiles in a given directory using QGIS 2.18. I do not want to navigate to the folder using QGIS GUI tools. Instead, I want my script to include all shapefiles in a certain location. For now, what I am getting, is a copy of one random file only. I suppose the semantics of my qgis:mergevecorlayers algorithm is not appropriate.

import glob, os, processing
path_to_shp = "C:/Temp/Tracks/"
os.chdir(path_to_shp)
for file in glob.glob("*.shp"):
    uri = path_to_shp + fname
    processing.runalg("qgis:mergevectorlayers", uri, "C:/Temp/Tracks/merged.shp")
3

You can calling the processing.runalg() within the for-loop. That means for every file, it will run the algorithm with only that file. Modify your script to first create a list of files and supply that list to the algorithm

import glob, os, processing
path_to_shp = "C:/Temp/Tracks/"
os.chdir(path_to_shp)
filelist = []
for fname in glob.glob("*.shp"):
    uri = path_to_shp + fname
    filelist.append(uri)

fileliststring = ';'.join(filelist)        
processing.runalg("qgis:mergevectorlayers", fileliststring, "C:/Temp/Tracks/merged.shp")

Note that this answer is for 2.18. In QGIS 3.x, you don't need to create a string with + characters between your file names. You can just supply the python list.

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.