QGIS – Renaming Shapefiles in QGIS Using PyQGIS

batchpyqgisqgisshapefiletable of contents

I have a huge list of layers in a project that are named in a foreign language. I want to translate and add the English title to the name.

When I right click on a layer and choose Properties -> General and change the layer name, it is visualized in the layer tree but the original file stays the same.

Is there a way to change the name of the original file from QGIS?

There are so many that searching them all in my folders would take too long.

Best Answer

QGIS 3.22

In QGIS 3.22 you have an option to rename layers using the context menu in QGIS Browser:

enter image description here

QGIS 2.x

For doing so, you would need to i) remove the layer from the ToC, ii) rename the files that conform the Shapefile (i.e., shp, dbf, shx, prj, and the like), and iii) load the renamed layer to QGIS. But we do need to automatize such workflow!

If you look at the steps, they're similar to what the Table Manager plugin does. So, I adapted such plugin's code to rename Shapefiles, you can find it here.

You can use it in this way (first try with a small backup project to see how it works):

  1. Rename your QGIS layers in the ToC, these new names will be taken to overwrite your corresponding Shapefiles names.

  2. Save your QGIS project in the same folder as the script rename_shapefiles.py

  3. Open the QGIS Python console.

  4. Copy the next code snippet there:

     from rename_shapes import RenameShapefiles
     for lyr in iface.mapCanvas().layers():
         rn = RenameShapefiles( iface, lyr )
         rn.doSave()
    

That's it! I've tested it on GNU/Linux, QGIS 2.6. The order of layers in the ToC varies after running the code.

Let me know if you have any issue.

If you need the layer order to be preserved, ask a new question, perhaps I can look at it :).

Related Question