[GIS] Split vector layer in PyQGIS

pyqgisqgisqgis-processingsplitting

I have a polygon shapefile that has several attributes.

I would like to know how can I create automatically a vector file for each one.

I already find split vector layer in QGIS (like picture):

enter image description here

but I want to use python.

I found a way through the web site at the following site, but this caused an error in QGIS.

https://docs.qgis.org/2.8/en/docs/user_manual/processing_algs/qgis/vector_general_tools/splitvectorlayer.html

enter image description here

>>> import processing
>>> processing.runalg('qgis:splitvectorlayer')
ERROR: Algorithm not found

So I need another way to split..

Best Answer

I'm not familiar with PyQGIS but this can be easily accomplished using ogr.

The following script shows an example:

from osgeo import ogr

fn = r""  # Vector Layer File path
driver = ogr.GetDriverByName('ESRI Shapefile')  # See OGR Vector Format for other options
dataSource = driver.Open(fn)
layer = dataSource.GetLayer()
sr = layer.GetSpatialRef()  # Spatial Reference

dst = r""  # Output directory
new_feat = ogr.Feature(layer.GetLayerDefn())  # Dummy feature

for id, feat in enumerate(layer):
    new_ds = driver.CreateDataSource(r"{}\feat_{}.shp".format(dst, id))
    new_lyr = new_ds.CreateLayer('feat_{}'.format(id), sr, ogr.wkbPolygon) 
    geom = feat.geometry().Clone()
    new_feat.SetGeometry(geom)
    new_lyr.CreateFeature(new_feat)

    del new_ds, new_lyr

You can, of course, change the name of the driver (in case your layer is not a shapefile) and the geometry of your new files (in case the input vector layer file is not a polygon).

More information about ogr vector formats here: http://www.gdal.org/ogr_formats.html

Related Question