[GIS] Iterating intersect between polylines and polygons in QGIS using Python script

pyqgis

I have a shapefile made up of 127 separate polygons that represent different districts. Overlaid on this layer is a polyline layer of 2800 streets, some which are completely bound by the polygons and some which crisscross two or more polygons.

My task is two find the total length of streets within each polygon (district). I've already done this with one district using Vector> Geoprocessing Tools > Intersect and then performing summary statsitics. However, in order to avoid doing this manually 127 times, I would like to write a script that will iterate through each polygon – performing the intersect with the polyline layer and leaving me with 127 separate shapefiles.

I not very familiar with Python – I only know some very basic commands. I've attached images to help you visualize and conceptualize the problem.

enter image description here

Best Answer

If you want to create separate shapefiles for each district, first make sure your polygon layer contains unique attributes (if not, you can create one using the Field Calculator with the expression $rownum). You can then run the Split Vector Layer from Vector > Data Management Tools > Split Vector Layer. Choose a directory (for example: C:/Users/you/Desktop/Test/Shapefiles//) and each polygon district should have its own shapefile.

The following script should intersect each polygon district with the line layer:

import glob, os, processing

line_layer = "path/to/line_layer//"    # This is the path to your line layer
poly_layers = "C:/Users/you/Desktop/Test/Shapefiles//"  # This is the path to your district shapefiles
output_dir = "path/to/output_dir//"    # This is the path for the shapefiles to be saved

os.chdir(poly_layers)
for fname in glob.glob("*.shp"):
    processing.runalg("qgis:intersection", line_layer, fname, output_dir + fname)
Related Question