1. 技术流程
(1)读取CSV文件和SHP文件,构成一一对应关系
(2)AddField_management,创新新字段
(3)UpdateCursor,更新字段
2.实例
# encoding: utf-8
import arcpy
import csv
import os
from arcpy import env
#读取CSV
def SearchFiles(directory, fileType):
fileList=[]
for root, subDirs, files in os.walk(directory):
for fileName in files:
if fileName.endswith(fileType):
fileList.append(os.path.join(root,fileName))
return fileList
directory = r'E:\cutpart_test\BuchongPoint\BuchongCSVchangeBi\BuchongCSVchange'
fileType = '.csv'
fileList = SearchFiles(directory, fileType)
print('Quantity of CSV:',len(fileList))
#读取pointshp
path_file=r"E:\cutpart_test\BuchongPoint\BuchongPointDonf"
ls = os.listdir(path_file)
shplist =[]
for i in ls:
if os.path.splitext(i)[1] == ".shp":
shppath = (path_file +"/"+ i)
shplist.append(shppath)
print('Quantity of SHP:',len(shplist))
env.workspace = path_file
#开始处理
for i in range(len(fileList)):
acsv = fileList[i]
ashp = shplist[i]
print(acsv,ashp)#查看是否为对应关系
#读取CSV
csvfile = open(acsv, 'rb') # 读文件内容
reader = csv.reader(csvfile)#,delimiter=","
lista = []
for col in reader:
x1 = float(col[-1])#我这里读取的是文件中的最后一列
lista.append(x1)
csvfile.close()
print('Quantity of DATA',len(lista))
print('读取CSV结束')
#创建字段
arcpy.AddField_management(ashp, 'pre_GRU', 'DOUBLE', field_length=len(lista))#我的新字段是'pre_GRU'
print("创建新字段结束")
# 更新
cursor = arcpy.UpdateCursor(ashp)
k = 0
for my_row in cursor:
my_value = my_row.getValue('pre_GRU')
my_row.setValue('pre_GRU', lista[k])
cursor.updateRow(my_row)
k += 1
print('存储结束')
print('Well done!')