4

Due to a clip-batchprocess and the tool "package layers" I end up with a geopackage with several layernames that start with "clip_". I would like to trim all the layernames by the first 5 characters instead of manually changing all the layernames. How can I do that?

enter image description here

I tried to use the following expression in the python console:

layerList = QgsProject.instance().layerTreeRoot().findLayers()
for layer in layerList:
    basename = layer.name()
    layer.setName(basename.replace("clip_",""))

But it doesn't work for me. The layer names don't change.

enter image description here

Enzo Baldini
  • 2,327
  • 1
  • 15
  • 29
  • Have a look to this solution which will do the trick: https://gis.stackexchange.com/a/329863/87346 – eurojam May 29 '21 at 04:46
  • Depends on whether these layers are loaded or not ... Could u make the context a bit more clear @Enzo Baldini ? – Snaileater May 29 '21 at 06:18
  • @Snaileater I can load the layers in the QGIS project if necessary. But the result should be to change the layer names in the geopackage (*.gpkg). I would like to have "bfn_ffh_gebiete" & "bfn_landschaftsschutzgebiete" etc. as the new layernames. This means to delete the first five charachters ("clip_") from each layername. – Enzo Baldini May 31 '21 at 14:30

1 Answers1

1

This is probably some sort of rules/agreements that sit behind the GeoPackage term in QGIS environment, because all imported vector and also attribute objects will have a prefix based on the .gpkg-file name and an empty space i.e. 'example layer_name' (example taken from: https://github.com/ngageoint/GeoPackage/blob/master/docs/examples/java/example.gpkg), but this does not work for rasters, see image below.

example

When I used your code:

layerList = QgsProject.instance().layerTreeRoot().findLayers()
for layer in layerList:
    basename = layer.name()
    layer.setName(basename.replace("example ","_"))

I got the following result:

result

So, I would assume you simply need to get the name of GeoPackage itself:

import os

layerList = QgsProject.instance().layerTreeRoot().findLayers()

for layer in layerList: source = qgis.utils.iface.activeLayer().dataProvider().dataSourceUri() geopackage_path = os.path.normpath(source.split('|')[0]) geopackage_name = geopackage_path.split(os.sep)[-1].split('.')[0] basename = layer.name() layer.setName(basename.replace("{} clip".format(geopackage_name),""))


References:

Taras
  • 32,823
  • 4
  • 66
  • 137