QGIS – Exporting Selected Features to Shapefile Using PyQGIS

pyqgisqgis

I am trying to develop a script to export selected features on a layer to enable some automation.

So far I have used this formula to import a layer and run a query. This ends up with features being selected on the layer.

import script

See result:

selected features

All good so far.

I now try to use the below script, found in a previous similar question:
QGIS Export Shapefile using PyQgis

It worked for the users in the post, however this returns the following error for me:

export error

I am quite new to Python so am not quite sure what's wrong. It is saying name 'i' is not defined, but I'm not sure what 'i' is trying to refer to?

I'm using QGIS 2.18.20.

Best Answer

The i in the post you linked to was referencing all layers that were loaded. So the code was iterating through each layer and saving their selected features.

Since you're only interested in one layer, replace i with layer and add the boolean selection parameter onlySelected:

_writer = QgsVectorFileWriter.writeAsVectorFormat(layer, 'C:/Datasets/South Oxfordshire Clipped LR INSPIRE.shp', "utf-8", None, "ESRI Shapefile", onlySelected=True)
Related Question