I have the following PyQGIS script with QGIS 3 that tries to ask for a layer, add a new field in that layer and modify the value of this field. But the code doesn't work. I get either Seems there is no valid script in the file when I use layer = QgsVectorLayer(Layer) or AttributeError: 'NoneType' object has no attribute 'isValid' when I use QgsProcessingUtils.mapLayerFromString :

context = QgsProcessingContext()
layer= QgsProcessingUtils.mapLayerFromString(Layer, context)


if layer.dataProvider().fieldNameIndex("new_col_name") == -1:
    layer.dataProvider().addAttributes([QgsField("new_col_name", QVariant.String)])

id_new_col= feuilles.dataProvider().fieldNameIndex("new_col_name")

for feature in layer.getFeatures():
  column_value= feature["column"]
  ... some operations ...
  layer.changeAttributeValue(feature.id(), id_new_col, new_column_value)


Not sure how to prompt for a layer, but working code below (with a shapefile) uses the currently selected layer. Note that the new field name was shortened due to name length constraints on shapefiles.

layer = iface.mapCanvas().currentLayer()

if layer.dataProvider().fieldNameIndex("new_col_na") == -1:
    layer.dataProvider().addAttributes([QgsField("new_col_na", QVariant.String)])

id_new_col= layer.dataProvider().fieldNameIndex("new_col_na")

for feature in layer.getFeatures():
    layer.changeAttributeValue(feature.id(), id_new_col, "val")


Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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