pyQGIS manually copy all features with attributes from a layer into a memory layer [depricated – see new post]]


my_WkbType = { 'WKBUnknown': 0, 'WKBPoint':1, 'WKBLineString':2, 'WKBPolygon':3, 'WKBMultiPoint':4, 'WKBMultiLineString':5, 'WKBMultiPolygon':6, 'WKBNoGeometry':7, 'WKBPoint25D':8, 'WKBLineString25D':9, 'WKBPolygon25D':10, 'WKBMultiPoint25D':11, 'WKBMultiLineString25D':12, 'WKBMultiPolygon25D':13 }

my_rev_WkbType = {v:k for k, v in WKBType_enum.items()}

input_layer = QgsVectorLayer('path/to/input/file.shp', "input layer", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(input_layer)
QGisWKBType=input_layer.dataProvider().geometryType()
EPSG_code=int(dp.crs().authid().split(":")[1])

destination_layer=QgsVectorLayer(my_rev_WkbType[QGisWKBType]+'?crs=epsg:'+str(EPSG_code)+'&index=yes','memory layer','memory')
destination_layer_data_provider=destination_layer.dataProvider()

input_layer_attrib_names = input_layer.dataProvider().fields()

oldattributeList = input_layer.dataProvider().fields().toList()
newattributeList=[]
for attrib in oldattributeList:
  if destination_layer.fieldNameIndex(attrib.name())==-1:
    newattributeList.append(QgsField(attrib.name(),attrib.type()))
destination_layer_data_provider.addAttributes(newattributeList)
destination_layer.updateFields()

destination_layer.startEditing()
cfeature = QgsFeature()
cfeatures=[]
xfeatures = input_layer.getFeatures()
for xfeature in xfeatures:
  xgeometry = xfeature.geometry()
  cfeature_Attributes=[]
  cfeature_Attributes.extend(xfeature.attributes())
  cfeature.setGeometry(xgeometry)
  cfeature.setAttributes(cfeature_Attributes)
  cfeatures.append(cfeature)
destination_layer_data_provider.addFeatures(cfeatures)
destination_layer_data_provider.commitChanges()

3 thoughts on “pyQGIS manually copy all features with attributes from a layer into a memory layer [depricated – see new post]]

  1. Awesome share!
    I do have a question; does ‘commitChanges’ command in line 35 apply to the dataProvider() or the layer itself?

    1. I also noticed, that the line 24 command results in duplicates of a single feature – while if it is moved inside the xfeature loop, each feature is appropriately added (via incremental variable overwrite).
      Maybe I am doing something wrong to cause this?

      1. Actually this is somewhat of a work in progress and I find tht when I use it I need to make the changes you have specified.
        I’d fix up the errors except I cant usually copy and paste my good code back in.
        I may get around to fixing it.
        Thanks for spotting though.

Leave a Reply

Your email address will not be published. Required fields are marked *


6 + two =