CSV TO SHAPEFILE - Using pyshp



我需要帮助。

我得到了一些带有地理信息的CSV文件,我需要将其转换为SHP...我正在尝试以下代码,但它不起作用。

这是我第一次使用python。如果您能帮助我,我将不胜感激。

import shapefile as shp
import csv
out_file = 'test.shp'
#Set up blank lists for data
lat,lon=[],[]
#read data from csv file and store in lists
with open('input.csv', 'rt') as csvfile:
r = csv.reader(csvfile, delimiter=';')
for i,row in enumerate(r):
if i > 0: #skip header
lat.append((row[0]))
lon.append((row[1]))
#Set up shapefile writer and create empty fields
w = shp.Writer(shp.POINT)
w.autoBalance = 1 #ensures gemoetry and attributes match
w.field('lat','F',10,8)
w.field('lon','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)

这就是 spyder 返回给我的内容:

Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.
IPython 6.4.0 -- An enhanced Interactive Python.
Traceback (most recent call last):
File "<ipython-input-1-dece8279ec6d>", line 1, in <module>
runfile('C:/Users/gcnxq/Downloads/py/csv.py', wdir='C:/Users/gcnxq/Downloads/py')
File "C:UsersgcnxqAppDataLocalContinuumanaconda3libsite-packagesspyderutilssitesitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:UsersgcnxqAppDataLocalContinuumanaconda3libsite-packagesspyderutilssitesitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/gcnxq/Downloads/py/csv.py", line 18, in <module>
w = shp.Writer(shp.POINT)
File "C:UsersgcnxqDownloadspyshapefile.py", line 1018, in __init__
self.shp = self.__getFileObj(os.path.splitext(target)[0] + '.shp')
File "C:UsersgcnxqAppDataLocalContinuumanaconda3libntpath.py", line 224, in splitext
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not int

我能够使用 arcpy 模块MakeXYEventLayer_management后跟 CopyFeatures_management 来完成此操作。下面的示例

import arcpy 
arcpy.env.workspace = r"C:/home"
csvFile = r"C:/home/some.csv"
in_x_field = "long"
in_y_field = "lat"
out_layer = "csvLayer"
spatial_reference = 4326
csvLayer=arcpy.MakeXYEventLayer_management(csvFile,in_x_field,in_y_field,out_layer,spatial_reference)
arcpy.CopyFeatures_management(csvLayer,"shapename.shp")

最新更新