[GIS] How to copy all feature attributes to a feature in a new layer

pyqgispythonqgis

I'm trying to create a new layer in QGIS based on an existing layer. The new features should have all the attributes of the corresponding features in the original layer. I've been trying to use outFeat.setAttributeMap(inFeat.attributeMap() ) similar to what Victor Olaya is doing at http://qgissextante.blogspot.de/2012/11/spliting-vector-layer.html, but all the attributes come out as NULL.

Could you tell me where the error is in my code?

def test(outputFilename):
 layer = qgis.utils.iface.activeLayer()
 provider = layer.dataProvider()
 fields = provider.fields()
 writer = QgsVectorFileWriter(outputFilename, "CP1250", fields, provider.geometryType(), provider.crs(), "ESRI Shapefile")
 inFeat = QgsFeature()
 outFeat = QgsFeature()
 inGeom = QgsGeometry()
 while provider.nextFeature(inFeat):
  point = inFeat.geometry().asPoint()
  inGeom = inFeat.geometry()
  outFeat.setGeometry(inFeat.geometry() )
  outFeat.setAttributeMap(inFeat.attributeMap() )
  writer.addFeature( outFeat )
 del writer
 newlayer = QgsVectorLayer(outputFilename, "Output", "ogr")
 QgsMapLayerRegistry.instance().addMapLayer(newlayer)

Best Answer

You are missing a provider.select() method call.

provider.select(provider.attributeIndexes() )
while provider.nextFeature(inFeat):
    ...