I have a script which performs various functions on shapefiles, most of which are polygon-based. However, some shapefiles are point-based and I have to specify where these files are by editing the script. Is there a technique in python which allows the script to identify which shapefiles are polygons, which are points, and run the necessary functions. I have provided a snippet (tested) of my script below which focuses primarily on polygon shapefiles and I have commented out the last line of code which includes the function I use for point shapefiles.
I am using QGIS 2.6.0.
##Test=name
import os
import glob
from os.path import expanduser
home = expanduser("~")
# Folder path of the directory and the "Results" folder
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
def run():
# Set directory and search for all .shp files
os.chdir(path_dir + "Shapefiles\\")
for fname in glob.glob("*.shp"):
# Clip .shp files with the polygon shapefile "Grid.shp" and save files to Result folder (How to specify this for polygons only?)
polygon_output=processing.runalg("qgis:clip", path_dir + "Grid.shp", fname, path_res + "/"+ fname)
# (How to identify point shapefiles and run the following command?)
# point_output=processing.runalg("qgis:distancetonearesthub", path_dir + "Grid.shp", fname, 'HubName', 0, 0, path_res + "/"+ fname)
run()
I managed to get a working script (even though the entire code could be vastly improved!).
##Test=name
import os
import glob
from qgis.core import *
from os.path import expanduser
home = expanduser("~")
# Folder path of the Results for shapefiles
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
def run():
# Set directory and search for all polygon .shp files
os.chdir(path_dir + "Shapefiles\\")
for fname in glob.glob("*.shp"):
shapefile = QgsVectorLayer( os.chdir(path_dir + "Shapefiles\\"), fname, "ogr" )
print shapefile.geometryType()
# Clip .shp files with the polygon shapefile "Grid.shp" and save files to Result folder
if shapefile.geometryType() == 3:
polygon_output=processing.runalg("qgis:clip", path_dir + "Grid.shp", fname, path_res + "/"+ fname)
# Use Distance to nearest hub function on point.shp files with the polygon shapefile "Grid.shp" as Hub layer and save files to Result folder
if shapefile.geometryType() == 3:
point_output=processing.runalg("qgis:distancetonearesthub", path_dir + "Grid.shp", fname, 'HubName', 0, 0, path_res + "/"+ fname)
run()