Reputation: 19
I have a code that converts csv files to shapefiles, but because my csv files do not have a header, the first line of data is replaced by the header in shp.writer. How can I add a header to the csv file before it is written as a shapefile?
import glob
import csv
import shapefile as shp
#lon, lat, count = [],[],[]
for filename in glob.glob('/data/kbrown/GLM/plots/test/hold/*.csv'):
revFilename =
filename.replace('/data/kbrown/GLM/plots/test/hold/*.csv',"")
rev2Filename = revFilename.replace(".csv","")
out_file = rev2Filename + '_temp.shp'
print(out_file)
with open(rev2Filename + '.csv') as f:
# writer = csv.DictWriter(f, fieldnames = ["Lat", "Lon", "Count"], delimiter = ";")
# writer.writeheader()
next(f)
r = csv.reader(f, delimiter=',')
lon, lat, count = [],[],[]
for row in r:
lon.append(float(row[0]))
lat.append(float(row[1]))
count.append(int(row[2]))
# f.close()
# print(lon)
w = shp.Writer(shapeType=shp.POINT)
# w.autoBalance = 1
w.field('lon', "F",10,10)
w.field('lat',"F",10,10)
w.field('count',"N",10)
w.autoBalance = 1
for j,k in enumerate(lat):
w.point(lon[j],lat[j])
w.record(lon[j], lat[j], count[j])
w.save(out_file)
w.shp.close()
w.shx.close()
w.dbf.close()
Example of csv before:
-135 0 13646
-135.2443500000 0.5356640000 44
-135.4915900000 1.0737620000 35
-135.7417600000 1.6142580000 24
-135.9949100000 2.1571150000 21
-136.2510900000 2.7022940000 18
Example of output:
lon lat count
-135.244353 0.535664 44
-135.491592 1.073762 35
-135.741763 1.614258 24
-135.994915 2.157115 21
-136.251098 2.702294 18
As you can see, the first line of data is deleted, and replaced by the header. How can I fix this? Any help would be appreciated.
Upvotes: 0
Views: 157
Reputation: 15533
Comment: I received the following error, TypeError:fieldnames is an invalid keyword argument for this function.
Switch to DictReader(...
r = csv.DictReader(f, fieldnames = ["Lat", "Lon", "Count"], delimiter = ",")
lon, lat, count = [], [], []
for row in r:
lon.append(float(row['Lon']))
lat.append(float(row['Lat']))
count.append(int(row['Count']))
Tested with Python: 3.4.2
Upvotes: 1