Renaming Shapefiles in QGIS?

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 download it from 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 :).


For R users, I wrote a quick R function that batch renames the .shp file and all files associated. It's pretty bare bones, and there is no error checking, etc., so if it fails you'll need to do a little investigation.

# Function to rename shapefile (.shp) and all associated files
# fpath = full file path of any of the associated files (character)
# newName = new name for the files (character)

renameShp <- function(fpath, newName) {
  dir <- dirname(fpath)
  base <- basename(fpath)
  fname <- strsplit(base, '[.]')[[1]][1]
  ls <- list.files(path=dir, pattern=fname, full.names=TRUE)
  sapply(ls, FUN=function(p){
    file.rename(from=p, to=sub(pattern=fname,replacement=newName, p))
  })
  print(paste("Renamed", length(ls), "files."))
}