2

I have a shapefile which resides in a folder, gets processed and the output is saved in another folder. Before the output, I would like to rename the shapefile slightly differently from the original:

eg.

"France (A).shp" -> "France (B).shp"

The following is the script I am using but comes up with a "cannot find file" error:

root_dir = "C:\Users\xxxx\Desktop\Test\\"
original_dir = 'Original files'
processed_dir = 'Processed files'

outputs_1=general.runalg("qgis:creategrid", 1000, 1000, 24108, 18351.157175, 258293.802316, 665638.226408, 1, 'EPSG:7405', None)

for path, subdirs, files in os.walk(root_dir):
    if original_dir in path:
        for file in files:
            if file.endswith('.shp'):
                newFile = rename(file, file.replace("(O).shp", "(P).shp"))
                outputs_2=general.runalg("qgis:clip", outputs_1['SAVENAME'], os.path.join(os.path.dirname(path), original_dir, file), os.path.join(os.path.dirname(path), processed_dir, newFile)

Is this the right way to go about changing the filename?

I also checked stackoverflow for some tips.

5
  • Sorry, didn't get it, you want your original Shapefile to be renamed in the original folder? or, you want your output Shapefile to have another name (rather than the original one)? Mar 31, 2015 at 13:13
  • @gcarrillo - Apologies, yes I want the output shapefile to have the other name.
    – Joseph
    Mar 31, 2015 at 13:15
  • Why don't you apply this solution: gis.stackexchange.com/questions/136568/… Mar 31, 2015 at 13:17
  • @gcarrillo - I played around with your method :). By using rename and replace instead of insert but kept getting errors.
    – Joseph
    Mar 31, 2015 at 13:19
  • 1
    @gcarrillo - Please post your comment as an answer, it works perfectly! =)
    – Joseph
    Mar 31, 2015 at 13:55

1 Answer 1

3

Following the idea from Cannot rename output file using standalone script for QGIS, I would do something like this:

for file in files:
  if file.endswith('.shp'):
    pieces = list(os.path.splitext(file)) 
    pieces[0]=pieces[0][:-3]+"(B)" 
    newFile = "".join(pieces)
    outputs_2=general.runalg("qgis:clip", outputs_1['SAVENAME'], os.path.join(os.path.dirname(path), original_dir, file), os.path.join(os.path.dirname(path), processed_dir, newFile)

This way you get the name of the file (with no extension), remove the last 3 characters (i.e., "(A)") and add the new ones (i.e., "(B)"). Then you add the extension and pass the new file name to the processing algorithm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.