PyQGIS: Shapefile from Selected Features


A common operation with vector layers is to select features based on attribute values and save those features to a new vector layer (i.e. shapefile). This tutorial will walk you through how to create a new shapefile from selected features. We’ll select some features, then save those features to a new shapefile.

First, we’ll open a vector layer that is already loaded into QGIS (stream_order) and visible in the table of contents.

layers = QgsProject.instance().mapLayersByName('stream_order')
layer = layers[0]

Select the features to save in a new file. In this example, features where the GRID_CODE attribute is equal to 4 are selected. See this post for more information about selecting features from a vector layer.

layer.selectByExpression('"GRID_CODE"=4')

Now create the new shapefile with QgsVectorFileWrite.writeAsVectorFormat(). In this function we specify the QgsVectorLayer (layer) to write, the filename (fn), file encoding, ogr driver name, and use onlySelected=True to specify that we want to write only selected features. The function returns an object that we can use to append additional features to the file, if desired. See this post for more information about creating vector files.

fn = 'C:/temp/outputs/select_gc4.shp'
writer = QgsVectorFileWriter.writeAsVectorFormat(layer, fn, 'utf-8', driverName='ESRI Shapefile', onlySelected=True)

Finally, we can add the new layer to the QGIS interface and delete the QgsVectorFileWriter object.

selected_layer = iface.addVectorLayer(fn, '', 'ogr')
del(writer)

Here is the full code block. The video at the end gives step-by-step instructions and demonstration of the process.

layers = QgsProject.instance().mapLayersByName('stream_order')
layer = layers[0]
layer.selectByExpression('"GRID_CODE"=4')

fn = 'C:/temp/outputs/select_gc4.shp'
writer = QgsVectorFileWriter.writeAsVectorFormat(layer, fn, 'utf-8', \
driverName='ESRI Shapefile', onlySelected=True)

selected_layer = iface.addVectorLayer(fn, '', 'ogr')

del(writer)

Konrad Hafen

Konrad has a Master's Degree in Ecology and a Doctorate Degree in Water Resources and has been performing geospatial analysis and writing code (in multiple programming languages) for over a decade. He writes code to develop models and analysis workflows to predict and evaluate changes to landscapes and water resources. He has published multiple articles in prominent peer-reviewed, scientific journals. Konrad's code and workflow contribute to operational products that inform water and ecosystem management.

Latest Tutorials