QGIS – Renaming GeoPackage Layer to Match GeoPackage File

batchgeopackagepythonqgisrename

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.

Best Answer

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

Related Question