Selecting all files in directory for merging in QGIS Processing?
You can simplify your script without using while...
and x
, x+1
: for simple Python list, it would be best to use for
or list comprehensions:
##Test=name
##Select_folder=folder
##Result=output vector
import os
import glob
# folder path of Result shapefile
path_res = os.path.dirname(Result)
# go to Select_folder
os.chdir(Select_folder)
# copy the shapefiles (you don't need to load the shapefiles, so use runalg)
for fname in glob.glob("*.shp"):
outputs_1 = processing.runalg("qgis:fieldcalculator", fname, 'Number', 1, 10, 0, True, 1 , path_res + "/"+ fname)
# paths of the shapefiles in the Result folder with list comprehension
output = [path_res + "/"+ shp for shp in glob.glob("*.shp")]
# merge the shapefiles
processing.runalg("saga:mergeshapeslayers", output[0], ";".join(output) , Result)
Some explications:
# folder path of the Result shapefile # = path_res
print os.path.dirname("/Users/Shared/test.shp")
/Users/Shared
# list comprehension
print [shp for shp in glob.glob("*.shp")]
['shape1.shp', 'shape2.shp',..., 'shapen.shp']
print [path_res + "/"+ shp for shp in glob.glob("*.shp")]
['/Users/Shared/shape1.shp', '/Users/Shared/shape2.shp', ...,'/Users/Shared/shapen.shp']
or better with os.path.join
(universal, Windows, Linux, Mac OS X):
print [os.path.join(path_res, shp) for shp in glob.glob("*.shp")]
print [os.path.join(path_res, shp) for shp in glob.glob("*.shp")][0] # = output[0]
/Users/Shared/shape1.shp
Found the answer thanks to @gene who's comments helped me focus on the right area. Just had to simply to use glob for the saga:mergeshapeslayers function to call:
multiple_0=glob.glob("*.shp")
Added this to the code above which now merges all files in the folder.