Monday, 13 March 2017

python - How to translate ESRI cursor example to pyQgis?


For example, how to translate this code into pyqgis?


    rows = gp.UpdateCursor("D:/St_Johns/data.mdb/roads")
row = rows.Next()

while row:
row.buffer_distance = row.road_type * 100

rows.UpdateRow(row)
print row
row = rows.Next()

errata: buffer_distance is a calculate column road_type is a calumn with calculate value


Follow your advice I type this code in to python windows:


>>> from qgis.core import QgsVectorLayer, QgsFeature
>>> layer = QgsVectorLayer(r"D:\fold", "boundingBoxes.shp", "ogr")
>>> road_type_index = layer.fieldNameIndex("road_type")
>>> buffer_distance_index = layer.fieldNameIndex("buffer_dis")

>>> layer.select(layer.pendingAllAttributesList())
>>> layer.startEditing()
True
>>> for feature in layer:
... newvalue = feature.attributeMap()[road_type_index].toInt()[0] * 100
... feature.changeAttribute(buffer_distance_index, newvalue)
... layer.updateFeature(feature)
...

next when I press "enter" the qgis (1.7.4) crash and exit




Answer



This should get you started


from qgis.core import QgsVectorLayer, QgsFeature
layer = QgsVectorLayer(r"D:\fold\boundingBoxes.shp", "boundingBoxes", "ogr")

road_type_index = layer.fieldNameIndex("road_type")
buffer_distance_index = layer.fieldNameIndex("buffer_distance")

layer.select(layer.pendingAllAttributesList())


layer.startEditing()
for feature in layer:
newvalue = feature.attributeMap()[road_type_index].toInt()[0] * 100
feature.changeAttribute(buffer_distance_index, newvalue)
layer.updateFeature(feature)

layer.commitChanges()

If in 1.7.4 try this


from qgis.core import QgsVectorLayer, QgsFeature

layer = QgsVectorLayer(r"D:\fold\boundingBoxes.shp", "boundingBoxes", "ogr")

road_type_index = layer.fieldNameIndex("road_type")
buffer_distance_index = layer.fieldNameIndex("buffer_distance")

layer.select(layer.pendingAllAttributesList())

layer.startEditing()
for feature in layer:
newvalue = feature.attributeMap()[road_type_index].toInt()[0] * 100

layer.changeAttributeValue(feature.id(),buffer_distance_index,newvalue)

layer.commitChanges()

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...