7

I have a GeoPackage file that has been renamed, but the layer inside the GeoPackage keeps the original name, is it possible to automatically put the same name on the layer as the file?

Example:
Original GeoPackage file : cidadedesaopaulo.gpkg
Layer name : citiesaopaulo

Renamed GeoPackage file : Cidades-SP_Brasil.gpkg
Layer name : citiesaopaulo
Desired layer name : Cidades-SP_Brasil

There are hundreds of files to change, which will be a lot of work to do manually. How can I automate this process in QGIS?

I'm aware of how GeoPackage works, but this filename pattern (the layer with the same name as the GeoPackage file) is a requirement of my employer. My question is if there is a way to change the layer name so that it has the same name as the GeoPackage. Whether using a programming language or the QGIS graphical modeler.

2
  • 1
    The geopackage itself is a container which can store multiple tables. It makes little sense to, as a default, change the content names when the object is copied. You can certainly rename contents as you wish (within format naming constraints). Please choose an intended environment, and include an attempt in that stack and an Edit to the Question.
    – Vince
    Mar 7, 2022 at 14:36
  • I think its a shame that a client would impose such a weird constraint upon a naming convention. Im sure there is some legacy requirement behind this but still, whats the point..... rant over.
    – nr_aus
    Mar 8, 2022 at 7:27

1 Answer 1

12

Try this. (You'll have to adjust it to match your exact data/situation)

import os 

geopackage_folder = r'/home/bera/Desktop'

for root, folder, files in os.walk(geopackage_folder):
    for file in files: #For all files in geopackage_folder, including all subdirectories
        if file.startswith('geopackage') and file.endswith('.gpkg'): #If the file is a geopackage named geopackage*.gpkg
            fullname = os.path.join(root, file) #Join path and filename together
            print(fullname)
            layer = QgsVectorLayer(fullname)
            for sublayer in layer.dataProvider().subLayers(): #Find the table(s) inside
                tablename = sublayer.split('!!::!!')[1]
                print(tablename)
                newname = file.split('.')[0]
                processing.run("native:spatialiteexecutesql", {'DATABASE':fullname,
                    'SQL':'ALTER TABLE {0} RENAME TO {1}'.format(tablename, newname)}) #Rename it

enter image description here

enter image description here

https://stackoverflow.com/questions/57015320/how-to-list-all-layers-on-geopackage-using-pyqgis

https://stackoverflow.com/questions/426495/how-do-you-rename-a-table-in-sqlite-3-0

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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