Export Shapefile – Using PyQGIS for Exporting

exportpyqgisqgisshapefile

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?

Best Answer

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.