2

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?

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
  • 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. – slalomchip Nov 21 '17 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? – artwork21 Nov 22 '17 at 3:18
0

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!!!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.