How to convert a CSV file to a shapefile in QGIS using Python

In this task, we will use python scripting for converting a Comma-Separated Values file (also known as CSV file) to a shapefile using PyQGIS.

We will use a sample dataset available from SpatialKey, which contains:

36634 records in Florida for 2012 from a sample company that implemented an aggressive growth plan in 2012.

We will only use the QGIS APIs for doing the task, using two different ways:

  • the first way is writing a new script from the Processing Toolbox using an input dialog (this is the most user-friendly solution 🙂 );
  • the second way is directly running the code without preliminarily loading the CSV file in the Layers Panel.

Solution writing a new script from the Processing Toolbox

The simplest and quickest way for performing the task is creating a custom script from the Processing Toolbox  (if you don’t know how to create a custom script, please see here, it is really easy to do!).

The following code will do the job (you only need to do a copy-and-paste operation to get it working!):

##Input_Table=table
##Longitude_Field=field Input_Table
##Latitude_Field=field Input_Table
##Coordinate_Reference_System=crs
##Output_Layer=output vector

from qgis.core import *
from processing.tools.vector import VectorWriter

spatRef = QgsCoordinateReferenceSystem(int(Coordinate_Reference_System.split(':')[1]), QgsCoordinateReferenceSystem.EpsgCrsId)

inp_tab = QgsVectorLayer(Input_Table, 'Input_Table', 'ogr')
prov = inp_tab.dataProvider()
fields = inp_tab.pendingFields()
outLayer = QgsVectorFileWriter(Output_Layer, None, fields, QGis.WKBPoint, spatRef)

pt = QgsPoint()
outFeature = QgsFeature()

for feat in inp_tab.getFeatures():
    attrs = feat.attributes()
    pt.setX(float(feat[Longitude_Field]))
    pt.setY(float(feat[Latitude_Field]))
    outFeature.setAttributes(attrs)
    outFeature.setGeometry(QgsGeometry.fromPoint(pt))
    outLayer.addFeature(outFeature)
del outLayer

Solution without writing a new script from the Processing Toolbox

If you don’t want to preliminarily load the CSV file in the Layers Panel, you may import it using Python (as we saw in this post).

Furthermore, you need to manually define:

  • the field name for the field containing the longitude value;
  • the field name for the field containing the latitude value;
  • the CRS to use;
  • the filepath for the output shapefile.

This will be a very easy task if you are a bit confident with PyQGIS. The following code is a slight edit of the previous one:

from qgis.core import *
from processing.tools.vector import VectorWriter

Input_Table = 'path_to_the_csv/input.csv' # set the filepath for the input CSV
lon_field = 'point_longitude' # set the name for the field containing the longitude
lat_field = 'point_latitude' # set the name for the field containing the latitude
crs = 4326 # set the crs as needed
Output_Layer = 'path_to_the_output/output.shp' # set the filepath for the output shapefile

spatRef = QgsCoordinateReferenceSystem(crs, QgsCoordinateReferenceSystem.EpsgCrsId)

inp_tab = QgsVectorLayer(Input_Table, 'Input_Table', 'ogr')
prov = inp_tab.dataProvider()
fields = inp_tab.pendingFields()
outLayer = QgsVectorFileWriter(Output_Layer, None, fields, QGis.WKBPoint, spatRef)

pt = QgsPoint()
outFeature = QgsFeature()

for feat in inp_tab.getFeatures():
    attrs = feat.attributes()
    pt.setX(float(feat[lon_field]))
    pt.setY(float(feat[lat_field]))
    outFeature.setAttributes(attrs)
    outFeature.setGeometry(QgsGeometry.fromPoint(pt))
    outLayer.addFeature(outFeature)
del outLayer

Regardless of the method used, this will be the result:

cover2

Welcome to Florida! 😎

Advertisements

One thought on “How to convert a CSV file to a shapefile in QGIS using Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s