Sunday, 19 April 2015

PyQGIS - Adding Fields to a Feature Layer


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?



Answer



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

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...