I'm trying to write a Python script with QGIS 3.4 but I have troubles when I want to change attributes values from a field.
With the code below, new values are calculated and the python console returns me True, but when I'm charging the layers in my QGIS Project, the attributes of all my features have a value = 0.000
.
My Python code looks like:
champs = couche.fields()
nom_champs = [champ.name() for champ in champs]
feature=couche.getFeatures()
for elem in feature:
elem.setAttribute('STD_2D', np.sqrt(elem[5]*elem[5]+elem[6]*elem[6]))
elem.setAttribute('STD_3D', np.sqrt(elem[5]*elem[5]+elem[6]*elem[6]+ elem[7]*elem[7]))
couche.changeAttributeValue(elem.id(), 11, elem.attributes()[11], skipDefaultValues=True)
couche.changeAttributeValue(elem.id(), 12, elem.attributes()[12], skipDefaultValues=True)
couche.dataProvider().updateExtents()
I think that they are not updated despite my command: couche.dataProvider().updateExtents()
. Do I need the other command like this one? Is it a problem due to how I'm writing my script?
I tried to find help with subjects like this one but without success.
Edit : I tried to use 'couche.startEditing()' or 'couche.commitChanges()' but when I'm doing that, the attributes of the field I have to change take no values. Attributes cases are blank.
If It can help, here are previous lines of my code:
if couche.isEditable() == False :
couche.startEditing()
res=couche.dataProvider().addAttributes([QgsField("STD_2D", QVariant.Double,len=5,prec=4), QgsField("STD_3D",QVariant.Double,len=5,prec=4)])
couche.updateFields()
Edit 2: For those who have the same probleme, I solved it by using the library "csv" with python, without PyGis. Then I import the new csv with PyGis in my current project.
import csv
entree = csv.reader(open("Export_QGIS_bon.csv","r"),delimiter=',')
sortie = csv.writer(open("Pour_shp.csv", "w"),delimiter=',')
row = next(entree)
row.insert(13,'STD_2D')
row.insert(14,'STD_3D')
sortie.writerow(row)
for row in entree:
row.insert(13,round(float(np.sqrt(float(row[5])*float(row[5])+
float(row[6])*float(row[6]))),3))
row.insert(14,round(float(np.sqrt(float(row[5])*float(row[5])+
float(row[6])*float(row[6])+float(row[7])*float(row[7]))),3))
sortie.writerow(row)
couche.startEditing()
and after modifications acouche.commitChanges()
?changeAttribute
method, you set value of the attribute to itself. So, the value in index 11 (and 12) doesn't changeç Did you notice?