Tuesday, 10 November 2015

Loading Multiple CSV Files into QGIS 2.10


How can I load multiple CSV files into QGIS with Longitude/Latitude already included in it. I downloaded the "Load Them All" plug-in, however, the result loaded was converted as text files and cannot be visualize on the map canvass. Any help? Are there any available plug-ins that can load multiple CSV file that will work fine in QGIS?



Answer



You could use the following code in the Python Console to locate your csv files in a specified folder and load them as point shapefiles using their longitude/latitude fields. The code assumes:




  • The csv file is comma-separated

  • The longitude/latitude field names are "x" and "y" respectively

  • The CRS of the loaded layers will be in EPSG:4326


But you can edit this:


import glob, os

# Define path to directory of your csv files
path_to_csv = "C:/Users/You/Desktop/csv folder/"


# Set current directory to path of csv files
os.chdir(path_to_csv)
# Find each .csv file and load them as vector layers
for fname in glob.glob("*.csv"):
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)




In the new version o QGIS, the command QgsMapLayerRegistry.instance().addMapLayer(lyr) was discountinued. The solution is still valid if we substitute the former line by: QgsProject.instance().addMapLayer(lyr) Also you need to delete or comment the second line from qgis.core import QgsMapLayerRegistry


The solution works perfectly.


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...