3

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'][0])):
 points.append(QgsPoint(shape['coordinates'][0][i][0],(shape['coordinates'][0][i][1])))
 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 True.

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?

Martin Hügi
3,6822 gold badges26 silver badges51 bronze badges
asked Nov 21, 2017 at 12:47

2 Answers 2

1

As out turns out, there were problems in the script. First, as @artwork21 pointed out, layer.updateFields() needed to be added update the fields in the layer. In addition, the fields also needed to be set in the features within the layer.

fields = layer.pendingFields()
poly.setFields(fields, True)

Here is the updated 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)])
layer.updateFields()
poly = QgsFeature()
fields = layer.pendingFields()
poly.setFields(fields, True)
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'][0])):
 points.append(QgsPoint(shape['coordinates'][0][i][0],(shape['coordinates'][0][i][1])))
 poly.setGeometry(QgsGeometry.fromPolygon([points]))
 poly.setAttribute('Object_ID', row['object_id'])
 pr.addFeatures([poly])
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
print "Completed!!!"
answered Nov 24, 2017 at 14:06
0

Since you are not in an edit session you may need to include the updateFields() method after adding the attribute:

After adding or removing fields in the data provider the layer’s fields need to be updated because the changes are not automatically propagated.

pr = layer.dataProvider()
attr = pr.addAttributes([QgsField('Object_ID', QVariant.String)])
layer.updateFields()
#...continue with logic
answered Nov 21, 2017 at 13:59
2
  • Your suggestion fixed an issue that I previously did not know I had, but it did not fix the key error issue. When I print the list of field names, Object_ID is printed. Commented Nov 21, 2017 at 18:33
  • Try adding a different field name to the memory layer like "test" and see if that works. Maybe Object_ID field cannot be created because it is a reserved key word? Commented Nov 22, 2017 at 3:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.