I'm writing a generic script which involves writing shapefiles to a directory which are then merged together. After writing the files out to the Output folder, I'm trying to get the saga:mergeshapeslayers algorithm to merge all the files in the Output folder. I have used the Model Builder and although it is helpful to an extent, I find that it is used for specific purposes whereas I am attempting to make a script for generic purposes.
Code:
##Test=name
##Select_folder=folder
##Result=output vector
import os
import glob
path_1 = Select_folder
path = path_1
os.chdir(path)
def function():
output = glob.glob(path_1 + './*.shp')
x = 0
while output[x]:
for fname in glob.glob("*.shp"):
outputs_1 = processing.runandload("qgis:fieldcalculator", output[x], 'Number', 1, 10, 0, True, 1 , "C:\Users\Me\Desktop\Output\\" + fname)
multiple_0 = glob.glob("*.shp")
x = x + 1
if x + 1 > len(output):
processing.runalg("saga:mergeshapeslayers", output[0], ";".join(multiple_0) , Result)
break
else:
continue
if path_1:
function()
else:
pass
Answer
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
No comments:
Post a Comment