7

I am trying to export selected feature using PyQGIS.

Till now I have tried these codes. After using this I can select feature but don't know how to export selected feature to new shapefile.

canvas = iface.mapCanvas()
AllLayers = canvas.layers()
for i in AllLayers:
    it = i.getFeatures(QgsFeatureRequest().setFilterExpression(u'"Country" = \'India\''))
    i.setSelectedFeatures([f.id() for f in it])
    print "Filter Applied"

Have tried this code: but this is just creating a duplicate of source file (I need selected only)

_writer = QgsVectorFileWriter.writeAsVectorFormat(i, r"C:\Users\XYZ\Desktop\NewFile.shp", "utf-8", None, "ESRI Shapefile")

If anybody knows how can I export shapefile using PyQGIS?

1
  • 1
    did you carfully read documentation about QgsVectorFileWriter.writeAsVectorFormat? qgis.org/api/… Commented Jul 5, 2015 at 9:32

1 Answer 1

8

As Luigi suggests, you can have a look at the API documentation, specifically to QgsVectorFileWriter::writeAsVectorFormat, and realize you're just missing one parameter (from the docs):

bool onlySelected = false, 

It says that the parameter onlySelected is of type boolean and is false by default. This parameter is right after the driver name. So, calling the function this way:

_writer = QgsVectorFileWriter.writeAsVectorFormat(i,r"C:\Users\XYZ\Desktop\NewFile.shp","utf-8",None,"ESRI Shapefile", True)

will export only the selected features from your layer.

0

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.