[GIS] How to convert CSV to point shapefile using Python

convertcsvpythonshapefile

import csv,sys
import osgeo.ogr, osgeo.osr #we will need some packages
from osgeo import ogr
from osgeo import *
import osgeo.osr as osr


def test():
    boolValue = True
    canvas = qgis.utils.iface.mapCanvas()
    spatialReference = osr.SpatialReference() #will create a spatial reference locally to tell the system what the reference will be
    spatialReference.ImportFromEPSG(4326) #here we define this reference to be the EPSG code
    driver = osgeo.ogr.GetDriverByName('ESRI Shapefile') # will select the driver for our shp-file creation.
    export_shp = r'E:\Folder'
    shapeData = driver.CreateDataSource(export_shp) #so there we will store our data
    outLayer = shapeData.CreateLayer(str('WaypointLayer'), spatialReference, osgeo.ogr.wkbPoint) #this will create a corresponding layer for our data with given spatial information.
    outDataSource = driver.Open(export_shp, 1)
    outLayer = outDataSource.GetLayer()
    layer_defn = outLayer.GetLayerDefn() # gets parameters of the current shapefile
    index = 0

# Reading the CSV file
    cnt = 0
    input_file = r'E:\Folder\CSV\points.csv' 
    with open(input_file, 'rb') as csvfile:
        readerDict = csv.DictReader(csvfile)


# Create the fields in the layer
        for header in readerDict.fieldnames:
            field_name = ogr.FieldDefn(header, ogr.OFTString)
            field_name.SetWidth(50)
            outLayer.CreateField(field_name)


        for row in readerDict:
            print (row['latitude'], row['longitude'])
            point = osgeo.ogr.Geometry(osgeo.ogr.wkbPoint)
            point.AddPoint(float(row['longitude']), float(row['latitude'])) #we do have LATs and LONs as Strings, so we convert them
            feature = osgeo.ogr.Feature(layer_defn)
            feature.SetGeometry(point) #set the coordinates
            feature.SetFID(index)

            for field in readerDict.fieldnames:
                i = feature.GetFieldIndex(field)
                feature.SetField(i, row[field])
            outLayer.CreateFeature(feature)
            index += 1
    shapeData.Destroy()
    outDataSource.Destroy()
    conLayer = QgsVectorLayer(export_shp,'pointLayer',"ogr")
    QgsMapLayerRegistry.instance().addMapLayer(conLayer)
    canvas.refresh()

The problem is that initially it is not updating the data in the attribute table but it creates the features when I executed once. When I executed again it is updating the field data. It sometimes create duplicates also.

What I am doing wrong here?

Best Answer

The question is "PyQGIS: How to convert the CSV to point shape file using python" and you only use ogr, Python only without PyQGIS.

In fact, you don't need PyQGIS or ArcPy, you can use Python only and there are alternatives to ogr, easier (Problem intersecting shapefiles with OGR in Python)