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.

1 Answer 1


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)
  • 1
    Brilliant thank you. My next task is to create a loop for this to run through 348 individually named shapefiles. However I will try this myself first before asking for help!
    – JClarkson
    Oct 10, 2018 at 10:17
  • @JClarkson - Most welcome, glad it helped and good luck :)
    – Joseph
    Oct 11, 2018 at 9:28
  • 5
    FYI in QGIS 3.8 I was getting "TypeError: QgsVectorFileWriter.writeAsVectorFormat(): arguments did not match any overloaded call: ... " - I had to replace the 'None' with layer.crs so the new format is -- _writer = QgsVectorFileWriter.writeAsVectorFormat(layer, 'd:/junk/test.shp', "UTF-8", layer.crs(), "ESRI Shapefile", onlySelected=True)
    – GeorgeC
    Sep 15, 2019 at 23:51
  • @GeorgeC - Good to know, thanks :)
    – Joseph
    Sep 17, 2019 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.