Thursday, 12 February 2015

coordinate system - Script to save lots of shapefiles into different CRS in QGIS


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?



Answer



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())

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...