[GIS] Converting CSV to Shapefile using pyshp

pyshppythonshapefile

I have a python script which converts csv data to shapefiles. It converts but won't get angle from csv.

Can anyone help me?

The CSV data looks like this:

fid_nr;x;y;angle
1;55.474040000;13.020460000;90
2;55.474040000;13.020460000;90

And the Python script is:

import shapefile as shp
import csv
import os
import sys

fileToOpen = open('test.csv', "rb")

#Set up blank lists for data
fid_nr,x,y,angle=[],[],[],[]

#read data from csv file and store in lists
with open(fileToOpen, 'rb') as csvfile:
    print "File found and will be now converted"
    r = csv.reader(csvfile, delimiter=";")
    for i,row in enumerate(r):
        print row
        if i > 0: #skip header
            fid_nr.append(row[2])
            x.append(float(row[0]))           
            y.append(float(row[1]))         
            angle.append(row[3])         

#Set up shapefile writer and create empty fields
w = shp.Writer(shp.POINT)
w.autoBalance = 1 #ensures gemoetry and attributes match
w.field("fid_nr","N")
w.field("x","F",10,8)
w.field("y","F",10,8)
w.field("angle","N")    

#loop through the data and write the shapefile
for j,k in enumerate(x):
    w.point(k,y[j]) #write the geometry
    w.record(k,y[j],fid_nr[j],x[j],y[j],angle[j])
#Save shapefile
w.save("Resultat/" + out_file3)
print "Done!"

Best Answer

You need to ensure that the angle read from the csv is cast as an integer and not a string as it may be at present. To do this change the line: angle.append(row[3]) to: angle.append(int(row[3]))

The second thing to correct is that you have not specified a length of the angle field, which can cause pyshp some problems, so specify a length, in this case 4 should be suitable:

w.field("angle","N",4)

These two fixes should allow the data to be written to the angle field of the attribute table.

Related Question