I have created two new fields into a shp table but I do not know how to add the atributes using PyQGis. I used to do from field calculator but in this case I need it to do using PyQGis.
Step 1; Adding fields, works properly:
Load a vector layer
#
## fn = 'c:/path/to/shapefile.shp'
# Path/nombre shp. En este caso solo el nombre
fn = 'C:/Users/juavafer/Proyectos/Costas_CoastSat/Output/Holanda/Shp/FromGeojson/Zona_Sur/Auto/Holanda_Sur_12_S2_ldcRef_Auto.shp'
layer = iface.addVectorLayer(fn, '', 'ogr')
# Get layer capabilities
#
caps = layer.dataProvider().capabilities()
# Add Fields
#
if caps & QgsVectorDataProvider.AddAttributes:
res = layer.dataProvider().addAttributes([QgsField('Fecha', QVariant.String, "string",10),
QgsField('LDC', QVariant.String,"string",25)])
layer.updateFields()
Step 2; Add values into 'Fecha' and 'LDC', DO NOT WORK:
-LDC = Ref_Auto -Fecha;
- Fecha = attribute( 'date')
- Fecha = replace("Fecha", '/','')
Where 'date' is an existing field in the attribute table. So, finally Fecha = YYYYMMDD.
I am trying with several posts with no results:
https://www.geodose.com/2018/09/qgis-python-tutorial-add-field-attribute.html
https://gis.stackexchange.com/questions/249555/adding-attributes-to-a-new-layer-in-pyqgis
Note: In this case each shp only has 1 row but others cases has many.