To add info to an existing layer instead of in memory layer you need to point to a layer on disk with QgsVectorLayer:
vl = QgsVectorLayer("C:\Temp\pt.shp", "pt", "ogr")
Then you may continue to reference the code snippet from this Q/A:
How to create a new empty vector layer programmatically?
I have a layer containing lots of elements of type Point, Line and Polygon
It is impossible in QGIS, look at how to open layers with multiple geometry types in qgis? ( only points layers, polylines layers or polygons layers and multi-parts geometries layers, MultiPoints, etc.).
So, no need of if geom.type()==QGis.Polygon
, unless the geometry type is QGis.MultiPolygon.
The correct syntax is (Geometry Handling):
a) Before iterating over the layer elements
layer = qgis.utils.iface.activeLayer()
if layer.wkbType()==QGis.WKBPolygon:
print 'Layer is a polygon layer'
if layer.wkbType()==QGis.WKBMultiPolygon:
print 'Layer is a multi-polygon layer'
b) during the iteration
print geom.type() # and the result is a value from QGis.GeometryType enumeration
print geom.wkbType() # same
Example in the Python console (different in a Plugin) with a simple polygon layer :
1) create the two empty shapefiles, layerAbove15 and layerBelow15
layer = qgis.utils.iface.activeLayer()
# source of the layer
provider = layer.dataProvider()
# creation of the shapefiles:
writer1 = QgsVectorFileWriter("layerAbove15Name.shp", "CP1250", provider.fields(), provider.geometryType(), provider.crs(), "ESRI Shapefile")
writer2 = QgsVectorFileWriter("layerBelow15Name.shp", "CP1250", provider.fields(), provider.geometryType(), provider.crs(), "ESRI Shapefile")
2) populate the shapefiles depending on the condition:
outelem = QgsFeature()
# iterating over the input layer
for elem in layer.getFeatures():
if len(elem.geometry().asPolygon()[0])-1 >=15:
outelem.setGeometry(elem.geometry() )
outelem.setAttributes(elem.attributes())
writer1.addFeature(outelem)
else:
....
writer2.addFeature(outelem)
3) with a simple function to avoid repetition:
def write(out,inp):
out.setGeometry(inp.geometry() )
out.setAttributes(inp.attributes())
return out
for elem in layer.getFeatures():
if len(elem.geometry().asPolygon()[0])-1 >=15:
writer1.addFeature(write(outelem,elem))
else:
writer2.addFeature(write(outelem,elem))
If the layer has multi-parts geometries (MultiPolygons), it is necessary to adapt the script consequently.
Best Answer
You are missing a
provider.select()
method call.