Answers:
pyshp模块很难掌握,但是一旦开始使用,它确实很有用。我编写了一个脚本,该脚本读取示例数据的csv并写出一个shapefile,并将数据存储为正确数据类型的属性。在我找到本本关于xbase格式的用户指南之前,pyshp / xbase数据类型一直对我来说很棘手,由于这个问题,我在自己的博客上写了一条有关pyshp数据类型的小注释,下面将其中部分内容进行了粘贴。 :
完整列表如下:
import shapefile as shp
import csv
out_file = 'GPS_Pts.shp'
#Set up blank lists for data
x,y,id_no,date,target=[],[],[],[],[]
#read data from csv file and store in lists
with open('input.csv', 'rb') as csvfile:
r = csv.reader(csvfile, delimiter=';')
for i,row in enumerate(r):
if i > 0: #skip header
x.append(float(row[3]))
y.append(float(row[4]))
id_no.append(row[0])
date.append(''.join(row[1].split('-')))#formats the date correctly
target.append(row[2])
#Set up shapefile writer and create empty fields
w = shp.Writer(shp.POINT)
w.autoBalance = 1 #ensures gemoetry and attributes match
w.field('X','F',10,8)
w.field('Y','F',10,8)
w.field('Date','D')
w.field('Target','C',50)
w.field('ID','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],date[j], target[j], id_no[j]) #write the attributes
#Save shapefile
w.save(out_file)
我希望这有帮助。
或者,您不需要将数据保存在列表中。
# import libraries
import shapefile, csv
# create a point shapefile
output_shp = shapefile.Writer(shapefile.POINT)
# for every record there must be a corresponding geometry.
output_shp.autoBalance = 1
# create the field names and data type for each.
# you can insert or omit lat-long here
output_shp('Date','D')
output_shp('Target','C',50)
output_shp('ID','N')
# count the features
counter = 1
# access the CSV file
with open('input.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
# skip the header
next(reader, None)
#loop through each of the rows and assign the attributes to variables
for row in reader:
id= row[0]
target= row[1]
date = row[2]
# create the point geometry
output_shp.point(float(longitude),float(latitude))
# add attribute data
output_shp.record(id, target, date)
print "Feature " + str(counter) + " added to Shapefile."
counter = counter + 1
# save the Shapefile
output_shp.save("output.shp")
您可以在此处找到此实现的有效示例。