CSV转换为SHAPEFILE-使用pyshp

时间:2018-09-05 20:27:30

标签: python 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)

这是间谍返回给我的东西:

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:\Users\gcnxq\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\gcnxq\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.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:\Users\gcnxq\Downloads\py\shapefile.py", line 1018, in __init__
    self.shp = self.__getFileObj(os.path.splitext(target)[0] + '.shp')

  File "C:\Users\gcnxq\AppData\Local\Continuum\anaconda3\lib\ntpath.py", line 224, in splitext
    p = os.fspath(p)

TypeError: expected str, bytes or os.PathLike object, not int

1 个答案:

答案 0 :(得分:0)

我能够使用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")