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!"
-
what do you mean when you say: 'wont get angle from csv'?Devdatta Tengshe– Devdatta Tengshe2012年11月21日 11:11:16 +00:00Commented Nov 21, 2012 at 11:11
2 Answers 2
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.
The problem I think is that you created four attributes
w.field("fid_nr","N")
w.field("x","F",10,8)
w.field("y","F",10,8)
w.field("angle","N")
but you tried to put six things on it
w.record(k,y[j],fid_nr[j],x[j],y[j],angle[j])
It should just be
w.record(fid_nr[j],x[j],y[j],angle[j])
If you want to add k and y[j] then you'd have to create the corresponding attributes/fields.
-
the geometry should be fine, your suggestion would also work but the value
k
is an iterator through the listx
, so will give the correct coordinates.sgrieve– sgrieve2012年11月21日 11:46:21 +00:00Commented Nov 21, 2012 at 11:46 -
Oops. That's rather embarrassing. Thanks for catching that :)R.K.– R.K.2012年11月21日 11:51:12 +00:00Commented Nov 21, 2012 at 11:51
-
No worries, I didn't notice the 6 attributes being written into 4 fields :)sgrieve– sgrieve2012年11月21日 11:53:10 +00:00Commented Nov 21, 2012 at 11:53