转载:https://blog.csdn.net/u012131430/article/details/90105857
根据自己的需求,对代码进行适当修改,并可以实现。
输入数据:一个文件夹下所有csv数据。
输出数据:一个文件夹下shp文件。
具体代码:
import arcpy
from arcpy import env
import glob
import os
import arcgisscripting
gp=arcgisscripting.create()
spatial_ref=arcpy.SpatialReference(4326)
env.workspace = r'存放csv数据的文件夹'
pathout = r'输出shp的文件夹'
x_corrods = 'lon'
y_corrods = 'lat'
h_te_best_fit = 'h_te_best_fit'
try:
for file1 in arcpy.ListFiles("*.csv"):
print file1
info = os.path.basename(file1).split('.')[0]
intable = file1
outlayer = info
print'outlayer',outlayer
gp.MakeXYEventLayer_management(intable,x_corrods,y_corrods,outlayer,spatial_ref,h_te_best_fit)
print'MakeXYEventLayer over'
gp.FeatureClassToShapefile_conversion(outlayer,pathout)
print'ToShapefile over'
except:
print gp.GetMessages()
更新20220606
上面代码适用于将少量参数转换,如果想csv中所有变量都转换为shp,可以采用下面的代码。
代码来源:csv2shp by python
import arcpy
import os
def csv2shp(csv_file, field_x, field_y, shape_file):
"""
Convert a CSV file with x/y fields into a Shapefile
"""
table_view = 'csv_file_as_view'
layer = 'xy_event_layer'
arcpy.MakeTableView_management(csv_file,table_view)
arcpy.MakeXYEventLayer_management(table_view,field_x,field_y,layer)
arcpy.CopyFeatures_management(layer, shape_file)
arcpy.Delete_management(table_view)
arcpy.Delete_management(layer)
if __name__ == '__main__':
input_files = [
r'D:\1.csv',
r'D:\2.csv'
]
output_location = r'D:\shp'
field_x = 'lon_20'
field_y = 'lat_20'
for input_file in input_files:
output_file = os.path.join(output_location, os.path.splitext(os.path.basename(input_file))[0] + '.shp')
print "Create %s" % output_file
csv2shp(input_file, field_x, field_y, output_file)
print('done!')
如果想批量转换,可以对代码进行修改:
import arcpy
import os
def csv2shp(csv_file, field_x, field_y, shape_file):
"""
Convert a CSV file with x/y fields into a Shapefile
"""
table_view = 'csv_file_as_view'
layer = 'xy_event_layer'
arcpy.MakeTableView_management(csv_file,table_view)
arcpy.MakeXYEventLayer_management(table_view,field_x,field_y,layer)
arcpy.CopyFeatures_management(layer, shape_file)
arcpy.Delete_management(table_view)
arcpy.Delete_management(layer)
if __name__ == '__main__':
input_files = os.listdir(r'D:\1')
output_location = r'D:\shp'
field_x = 'lon_20'
field_y = 'lat_20'
for input_file in input_files:
filename = os.path.splitext(input_file)
output_file = os.path.join(output_location,filename[0] + '.shp')
print "Create %s" % output_file
csv2shp(r'D:\1\\'+input_file, field_x, field_y, output_file)
print('done!')
报错及处理:
1.ExecuteError: Failed to execute. Parameters are not valid. ERROR 000732
报错原因:数据集不存在或不受支持。
出现这类错误最主要的原因就是路径格式不规范:
• 文件夹名称拼写错误
• 使用了反斜杠而不是正斜杠
• 路径名称中有空格
报错的代码: input_files = os.listdir('D:\1')
修改后的代码: input_files = os.listdir(r'D:\1')
添加了r
2.AttributeError: 'list' object has no attribute 'replace'
报错原因:list对象没有replace方法,str对象才有,在list对象上调用replace当然会报AttributeError。
解决方法:str(),将list转换成str。