Splitting a shapefile

Sometimes, you need to split a shapefile in order to break a larger dataset into more manageable sizes or 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 of how to write processing scripts.

Getting ready

We will split a census tract shapefile by county. You can download the sample zipped shapefile from https://geospatialpython.googlecode.com/files/GIS_CensusTract.zip.

  1. Extract the zipped shapefile to a directory named /qgis_data/census.
  2. You also need the following script for the Processing Toolbox:
    https://geospatialpython.googlecode.com/svn/Split_vector_layer_by_attribute.py
    
  3. Next, use the following steps to add the script to the Processing Toolbox:
  4. Download the script to your /qgis_data/ directory.
  5. In the QGIS Processing Toolbox, open the Scripts tree menu and then go to the Tools submenu.
  6. Then, double-click on the Add script from file command.
  7. In the File dialog, navigate to the script. Select the Script and click on the Open button.

The stage is set now. Perform the steps in the next section to split the shapefile.

How to do it...

This recipe is as simple as running the algorithm and specifying the filename and data attribute. Perform the following steps:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. Import the processing module:
    import processing
    
  4. Define your data directory as a variable to shorten the processing command:
    pth = "/qgis_data/census/"
    
  5. Finally, run the algorithm:
    processing.runalg("script:splitvectorlayerbyattribute",pth + "GIS_CensusTract_poly.shp","COUNTY_8",pth + "split")
    

How it works...

The algorithm will dump the split files in the data directory, numbered sequentially.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset