I'm building my first script purposed to :
- Create fields if they doesn't already exist
- Fill value in this fields
The code works, but I have to perform it 2 times when the case requierts to Add Fields (when they did not already exist). In fact, when I launch the code the first time, it adds fields missing but it doesn't fill fields and I get an error message :
The fields -1 of the feature n°... doesn't exist.
Fields are now built and if I re launch the script, I do not get error anymore and it fills the fields.
How can I fix my script to enable it to perform both parts at the first launch?
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
from xml.etree import ElementTree as ET
layer = iface.activeLayer()
dpr = layer.dataProvider()
apr_ind = layer.fields().indexFromName("apr")
# add fields
fields_arr = [("apr", QVariant.Double)]
flds = [QgsField(i[0], i[1]) for i in fields_arr if i[0] not in [fld.name() for fld in layer.fields()]]
layer.dataProvider().addAttributes(flds)
layer.updateFields()
# field update
layer.updateFields()
layer.startEditing()
for feature in layer.getFeatures():
file_path = feature["Path"]
print(file_path)
img = Image.open(file_path)
exif = { TAGS[k]: v for k, v in img._getexif().items() if k in TAGS }
with open(file_path, "rb") as f:
s = str(f.read())
start = s.find('<x:xmpmeta')
end = s.find('</x:xmpmeta')
xmp = s[start:end+12].replace("\\n","\n")
tree = ET.XML(xmp)
apr = exif["FNumber"][0]/exif["FNumber"][1]
dpr.changeAttributeValues({ feature.id():{apr_ind: apr }})
layer.commitChanges()
print("COMPLETED")
changeAttributeValues()
method won't work.