使用python 2.7将.CSV文件转换为点要素类

时间:2013-04-03 14:56:28

标签: python csv python-2.7

我有一个包含75列和近4000行的.CSV文件。我需要为整个.CSV文件创建一个shapefile(点),每列作为一个字段。需要将所有75列引入新的shapefile,每列代表一个字段。

这个话题似乎已经有了很多,但我能找到的所有内容都是针对少量列的.csv文件。

https://gis.stackexchange.com/questions/17590/why-is-an-extra-field-necessary-when-creating-point-shapefile-from-csv-files-in

https://gis.stackexchange.com/questions/35593/using-the-python-shape-library-pyshp-how-to-convert-csv-file-to-shp

这个脚本看起来接近我需要完成的任务,但它又为.CSV中的每一列添加了一个字段,在这个例子中有三个字段; DATE,LAT,LON。

import arcpy, csv
arcpy.env.overwriteOutput = True

#Set variables
arcpy.env.workspace = "C:\\GIS\\StackEx\\"
outFolder = arcpy.env.workspace
pointFC = "art2.shp"
coordSys = "C:\\Program Files\\ArcGIS\\Desktop10.0\\Coordinate Systems" + \
           "\\Geographic Coordinate Systems\\World\\WGS 1984.prj"
csvFile = "C:\\GIS\\StackEx\\chicken.csv"
fieldName = "DATE1"

#Create shapefile and add field
arcpy.CreateFeatureclass_management(outFolder, pointFC, "POINT", "", "", "", coordSys)
arcpy.AddField_management(pointFC, fieldName, "TEXT","","", 10)

gpsTrack = open(csvFile, "r")

headerLine = gpsTrack.readline()
#print headerLine
#I updated valueList to remove the '\n'
valueList = headerLine.strip().split(",")
print valueList
latValueIndex = valueList.index("LAT")
lonValueIndex = valueList.index("LON")
dateValueIndex = valueList.index("DATE")

# Read each line in csv file
cursor = arcpy.InsertCursor(pointFC)
for point in gpsTrack.readlines():

   segmentedPoint = point.split(",")
   # Get the lat/lon values of the current reading                    
   latValue = segmentedPoint[latValueIndex]
   lonValue = segmentedPoint[lonValueIndex]
   dateValue = segmentedPoint[dateValueIndex]
   vertex = arcpy.CreateObject("Point")
   vertex.X = lonValue
   vertex.Y = latValue
   feature = cursor.newRow()
   feature.shape = vertex
   feature.DATE1 = dateValue
   cursor.insertRow(feature)

del cursor

是否有更简单的方法使用python创建shapefile而不为.CSV文件中的所有75列添加字段?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

只需选择您需要的列;您不是必需来使用所有列。

使用csv module读取文件,然后从每行中选出2个值:

import csv

cursor = arcpy.InsertCursor(pointFC)
with open('yourcsvfile.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        point = arcpy.CreateObject("Point")
        point.X, point.Y = float(row[5]), float(row[27])  # take the 6th and 28th columns from the row
        cursor.insertRow(point)