Splitting a shapefile
Sometimes you need to split a shapefile to break a larger dataset into more manageable sizes, or you want to isolate a specific area of interest. There is a script in the Processing Toolbox that splits a shapefile by attribute. It is very useful, even though it is provided as an example on how to write processing scripts.
Getting ready
We will split a census track shapefile by county. You can download the sample zipped shapefile from the following URL:
https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
Extract the zipped shapefile to a directory named /qgis_data/census
.
How to do it...
This recipe is as simple as running the algorithm and specifying the file name and data attribute:
- Start QGIS.
- From the Plugins menu, select Python Console.
- Import the
processing
module:import processing
- Define our data directory as a variable to shorten the processing command:
pth = "/qgis_data/census/"
- Finally, run the algorithm:
processing.runalg("script:splitvectorlayerbyattribute",pth + "GIS_CensusTract_poly.shp","COUNTY_8", pth + "split")
How it works...
This algorithm splits the data by grouping like attributes. It will will dump the split files in the data directory numbered sequentially. You can select the directory, but not the file names. Because this is a processing Python script, however, you can easily copy and edit it to change the way it works. In QGIS 2.18 there is also a similar OGR function named Split vector layer.