1

In order to let a script fill specific attributes fields, I need help to build a Python function that creates the fields that have not already been built.

from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS

layer = iface.activeLayer()
dpr = layer.dataProvider()

#  ==> The fields bellow have to be created at this stage

apr_ind = layer.fields().indexFromName("apr")
iso_ind  = layer.fields().indexFromName("iso")
exp_ind  = layer.fields().indexFromName("exp")
foca_ind  = layer.fields().indexFromName("foca")
foca35_ind  = layer.fields().indexFromName("foca35")
shsp_ind  = layer.fields().indexFromName("shsp")
fyd_ind = layer.fields().indexFromName("fyd")
gyd_ind = layer.fields().indexFromName("gyd")
ra_ind  = layer.fields().indexFromName("ra")

...
4

Here's an example, I'll let you change the field type!

layer = iface.activeLayer()
dpr = layer.dataProvider()

# add fields
dpr.addAttributes([QgsField("apr", QVariant.String),
                  QgsField("iso",  QVariant.Int),
                  QgsField("exp", QVariant.Double),
                  QgsField("foca", QVariant.Double),
                  QgsField("foca35", QVariant.Double),
                  QgsField("shsp", QVariant.Double),
                  QgsField("fyd", QVariant.Double),
                  QgsField("gyd", QVariant.Double),
                  QgsField("ra", QVariant.Double),])

# field update
layer.updateFields()

# check if a field exist 
field_index = layer.fields().indexFromName("apr")
print(field_index) # -1 if the field doesn't exist

| improve this answer | |
  • hey @Vincent Bré , thanks . Sometimes some fields aready exists.. then I would like to only build fields that doesn't exist. How can we do this check? – zlikotp Dec 17 '19 at 8:25
  • @zlikotp I edited my post – Vincent Bré Dec 17 '19 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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