2

I would like to repeat this script on hundreds of layers using PyQGIS 3.16.

I wanted to import it in the Modeler from the QGIS toolbox and then run the script in a batch process to select my hundreds of layers. The problem is that I can't switch from the Python console to the QGIS toolbox, I systematically get errors ("iface is not defined", "SyntaxError: (unicode error) 'utf8' codec can't decode byte 0x8e....") and I can't solve them... I also tried to make the script in the same table according to the attributes of a field "name" to repeat it when the name of the object changes but nothing happens using the function: "getFeature()" but the loop does not happen.

Would you have a solution?

from qgis.utils import iface
from PyQt5.QtCore import QVariant

layer = iface.activeLayer() #Click layer in layer tree
idfield = 'num_page_1' #Change to match the name of your field


coords = [[round(f.geometry().centroid().asPoint().x(),0),round(f.geometry().centroid().asPoint().y(),0),f.id()] for f in layer.getFeatures()]
coords.sort(key=lambda k: (k[1],-k[0]), reverse=True)
order = [i[2] for i in coords]

i = layer.fields().indexFromName(idfield)
attrMap = {id: {i:e} for e,id in enumerate(order,1)}
layer.dataProvider().changeAttributeValues(attrMap)
0
4

List the geopackages and layers like this:

import os
geopackage_folder = r'/home/bera/GIS/Data/testdata'

for item in os.listdir(geopackage_folder): #List everything in the folder above.
    fullname = os.path.join(geopackage_folder, item)
    if fullname.endswith('.gpkg'): #Find the geopackages
        print(item)

        #Process each geopackage layer
        layer = QgsVectorLayer(fullname,"test","ogr") #https://stackoverflow.com/questions/57015320/how-to-list-all-layers-on-geopackage-using-pyqgis
        subLayers = layer.dataProvider().subLayers()
        for subLayer in subLayers:
            name = subLayer.split('!!::!!')[1]
            print(name)
            uri = "%s|layername=%s" % (fullname, name,)
            subLayer = QgsVectorLayer(uri, name, 'ogr')
            
            #Do something with subLayer (one geopackage table) here
0

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.