I have a map, in which each region is defined as an attribute of the map (I can select each region from the attribute table). I am trying to create new layers each one containing only 1 region using Python (quite like the gui command " save selection as..").
I have got so far (I am very new to Python, so forgive all the obvious errors I have made here):
from qgis.core import *
from qgis.gui import *
layer_Map = canvas.layer(0) #select the layer
provider = layer_Map.dataProvider()
fields = provider.fields()
writer = QgsVectorFileWriter("P:\Qgis\Output\Writer.shp", "CP1250", fields,provider.geometryType(), provider.crs(), "ESRI Shapefile")
Selection = layer_Map.select(1) #This selects the region of the map I want to write in the new layer
writer.addFeature(Selection) #this is clearly wrong, as I get an error
Best Answer
Try the Unique_values_saver plugin for QGIS. It allows you to save one vector layer for each unique value from a specific field.
For instance, for a layer with world countries and regions, I've generated 10 vector layers, each one corresponding to a different region.
If you need the way to do it in Python, just have a look at the source code of the plugin, specifically at the uniqueValues method: