If you're looking to reproject csv files from the Python Console in QGIS then you could use the following script. All you would need to change are the three paths which are mentioned in the comments.
Essentially, the script imports your csv files into QGIS as shapefiles (assuming your geometric fields are named X
and Y
). It then uses the qgis:reprojectlayer
and qgis:fieldcalculator
algorithms from the Processing Toolbox to reproject and update the X
and Y
fields with the new coordinates. It then saves these in a folder and converts them to csv files in a path you specify. So in the end, you have updated shapefiles and csv files in separate folders.
import glob, os, processing
path_to_csv = "C:/Users/You/Desktop/Testing//" # Change path to the directory of your csv files
shape_result = "C:/Users/You/Desktop/Testing/Shapefile results//" # Change path to where you want the shapefiles saved
os.chdir(path_to_csv) # Sets current directory to path of csv files
for fname in glob.glob("*.csv"): # Finds each .csv file and applies following actions
uri = "file:///" + path_to_csv + fname + "?delimiter=%s&crs=epsg:4326&xField=%s&yField=%s" % (",", "x", "y")
name = fname.replace('.csv', '')
lyr = QgsVectorLayer(uri, name, 'delimitedtext')
QgsMapLayerRegistry.instance().addMapLayer(lyr) # Imports csv files to QGIS canvas (assuming 'X' and 'Y' fields exist)
crs = 'EPSG:32633' # Set crs
shapefiles = QgsMapLayerRegistry.instance().mapLayers().values() # Identifies loaded layers before transforming and updating 'X' and 'Y' fields
for shapes in shapefiles:
outputs_0 = processing.runalg("qgis:reprojectlayer", shapes, crs, None)
outputs_1 = processing.runalg("qgis:fieldcalculator", outputs_0['OUTPUT'], 'X', 0, 10, 10, False, '$x', None)
outputs_2 = processing.runalg("qgis:fieldcalculator", outputs_1['OUTPUT_LAYER'], 'Y', 0, 10, 10, False, '$y', shape_result + shapes.name())
os.chdir(shape_result) # Sets current directory to path of new shapefiles
for layer in glob.glob("*.shp"): # Finds each .shp file and applies following actions
new_layer = QgsVectorLayer(layer, os.path.basename(layer), "ogr")
new_name = layer.replace('.shp', '')
csvpath = "C:/Users/You/Desktop/Testing/CSV results/" + new_name + ".csv" # Change path to where you want the csv(s) saved
QgsVectorFileWriter.writeAsVectorFormat(new_layer, csvpath, 'utf-8', None, "CSV")
Hope this helps!