6

I have a lot of shapefiles that I need to save in a different CRS... is it possible to automate this process with a script in QGIS?

  • Are the shapefiles already loaded into QGIS or do they reside in the same directory? – Joseph Feb 16 '16 at 14:41
  • I was thinking about exporting the shapefiles already loaded but for me it's the same... – Bryan Ciceri Feb 16 '16 at 14:45
11

For shapefiles already loaded into QGIS, you can use the following code in the Python Console:

import processing

# Set path to where you want the shapefiles saved
shapes_result = "path/to/results//" 
# Set crs
crs = 'EPSG:4326'  

shapefiles = QgsMapLayerRegistry.instance().mapLayers().values() 
for shapes in shapefiles:
        processing.runalg("qgis:reprojectlayer", shapes, crs, shapes_result + shapes.name())

I used QGIS 2.12.3-Lyon with Processing plugin version 2.12.2.


Edit:

The following code which you can run as a script reprojects the loaded layers in QGIS and saves them in their original folder. Note that they are prefixed with "New_" as you won't be able to overwrite the shapefiles (since they're already in use):

##Reproject shapefiles=name

import os, processing
from qgis.core import QgsMapLayerRegistry

# Set crs
crs = 'EPSG:4326'  

shapefiles = QgsMapLayerRegistry.instance().mapLayers().values() 
for shapes in shapefiles:
    myfilepath = shapes.dataProvider().dataSourceUri()
    (myDirectory,nameFile) = os.path.split(myfilepath)
    processing.runalg("qgis:reprojectlayer", shapes, crs, myDirectory + "/" + "New_" + shapes.name())
  • I tested the code... it works properly if I run it into the Python Console, but it generates an error (name 'QgsMapLayerRegistry' is not defined) if I execute it as a script... I was also thinking if it is possible to export the shapefiles to the path of their "original" (suppose I have loaded shapefiles from different folders) – Bryan Ciceri Feb 16 '16 at 15:21
  • @BryanCiceri - Yes, the code was meant for the Python Console. I've edited my post to include a code which you can run as a script, it also saves the layers in their original locations with a slightly new file name =) – Joseph Feb 16 '16 at 15:48
  • Excuse me @Joseph, but sometimes I obtain the "[Errno 9] Bad file descriptor"... and the script stops... do you know how can I fix it or handle it in order to make the script continue? – Bryan Ciceri Feb 16 '16 at 18:06
  • @BryanCiceri - Hmm make sure you have permission to write to the directory of the shapefiles you loaded. Also make sure there are only shapefiles loaded and not rasters. I can't seem to replicate your issue here. – Joseph Feb 18 '16 at 10:27
  • I dunno why but if I run the script again after the error it doesn't stop no more and ends correctly... – Bryan Ciceri Feb 18 '16 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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