I'm new to PyQGIS and am having difficulty adding fields to a feature. I want to plot footprints and assign attributes to each of the footprints. Here is my script.
import csv, ast from PyQt4.QtCore import QFileInfo, QVariant fileName = 'C:\\directoryname\\temp.csv' layer = QgsVectorLayer('Polygon?crs=EPSG:4326', 'poly', 'memory') pr = layer.dataProvider() attr = pr.addAttributes([QgsField('Object_ID', QVariant.String)]) poly = QgsFeature() with open(fileName) as f: rows = csv.DictReader(f) for row in rows: shape = ast.literal_eval(row['footprint']) points =  for i in range(0,len(shape['coordinates'])): points.append(QgsPoint(shape['coordinates'][i],(shape['coordinates'][i]))) poly.setGeometry(QgsGeometry.fromPolygon([points])) poly.setAttribute('Object_ID', row['object_id']) pr.addFeatures([poly]) layer.updateExtents() QgsMapLayerRegistry.instance().addMapLayers([layer]) print "Completed!!!"
I receive the error
File "c:/directoryname/tmp9urit7.py", line 19, in poly.setAttribute('Object_ID', row['object_id']) KeyError: 'Object_ID'
When I add the line
caps_string = layer.dataProvider().capabilitiesString(), then printing caps_string yields that I have full privileges to add, modify, and delete features and attributes.
Also, when I
print attr, the result is
If I comment out the line poly.setAttribute('Object_ID', row['object_id']), the script plots the footprints and completes without error, but I have no attributes for any of the footprints.
What am I doing wrong?