Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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
share|improve this question

2 Answers 2

You can't write the selection directly; you have to iterate over the selected features:

# write each feature to the shapefile
for feature in Selection:

# close the writer and flush features to disk
del writer
share|improve this answer
thanks for the contribution gsherman, but that did not seem to solve the issue.. If I try to iterate on Selection as you suggest I get the following error: TypeError: 'NoneType' object is not iterable –  Dom Mar 20 '13 at 15:51
That means your select statement didn't return any features. –  gsherman Mar 20 '13 at 19:18
Right. But I still see the region of the map correctly highlighted.. –  Dom Mar 21 '13 at 17:02

Try the Unique_values_saver plugin for QGIS. It allows you to save one vector layer for each unique value from a specific field.

enter image description here

For instance, for a layer with world countries and regions, I've generated 10 vector layers, each one corresponding to a different region.

enter image description here

If you really need the way to do it in Python, just have a look at the source code of the plugin.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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