Rename layers with PyQGIS script
setLayerName()
will rename the layer:
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
layer.setLayerName('NewName')
Since 2.16 it's QgsMapLayer.setName('thenewname')
Since 3.x it's:
for layer in iface.layerTreeView().selectedLayers():
layer.setName('NewName')
This script (for QGIS 3) iterates over all layers in the project and replaces chosen text in their name. Simply paste this inside the QGIS Python Console. This works for QGIS 3
layerList = QgsProject.instance().layerTreeRoot().findLayers()
for layer in layerList:
basename = layer.name()
layer.setName(basename.replace("db_prefix_to_be_followed_by_a_space ",""))
or, if you wish to do this only over selected layers in the layer panel:
for layer in iface.layerTreeView().selectedLayers():
basename = layer.name()
layer.setName(basename.replace("db_prefix_to_be_followed_by_a_space ",""))
(do not forget to put the offending space inside the first quotation marks) (the empty text inside the second quotation marks will effectively erase the text found in the first quotation marks)
This will serve when adding a database (such as gpkg or fgdb) to a project to remove the database name prefixed on the layer name. This will also make it easier to reference those layers in the DB_manager because the spaces in the names are not compatible with the autocomplete. (as of 3.8)
The other answer as well as this other question (Stuck on how to list loaded layers in QGIS 3 via Python) got me to come up with this complete solution.
Also, as seen in the other answer, use this for QGIS 2
QgsMapLayerRegistry.instance().mapLayers().values():