I am trying create new columns in an attribute table and fill them with values with expressions using python consolePython Console in QGIS.
I successfully create the new columns but when I try to fill them, I get an assertion error. Here is an example for one column :
layer=QgsVectorLayer(r"C:\Users\ANI\Documents\SIG\fossés\pythontest\mergedlinef1.shp")
features=layer.getFeatures()
layer_provider=layer.dataProvider()
layer_provider.addAttributes([QgsField("long",QVariant.Double)])
layer.updateFields()
layer.startEditing()
exp_long = QgsExpression("$length")
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
with edit(layer):
for f in layer.getFeatures():
context.SetFeature(f)
f['long'] = exp_long.evaluate(context)
layer.updateFeature(f)
layer=QgsVectorLayer(r"C:\Users\ANI\Documents\SIG\fossés\pythontest\mergedlinef1.shp")
features=layer.getFeatures()
layer_provider=layer.dataProvider()
layer_provider.addAttributes([QgsField("long",QVariant.Double)])
layer.updateFields()
layer.startEditing()
exp_long = QgsExpression("$length")
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
with edit(layer):
for f in layer.getFeatures():
context.SetFeature(f)
f['long'] = exp_long.evaluate(context)
layer.updateFeature(f)
And the error :
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 23, in <module>
File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python\qgis\core\additions\edit.py", line 38, in __enter__
assert self.layer.startEditing()
AssertionError
Line 23 refers to the line with edit(layer):
.
What What am I doing wrong ?