【代码】批量 CSV转SHP
程序员文章站
2022-05-26 14:05:54
...
import os
import csv
import codecs
import shapefile
# 实现csv到shp的转变
def trans_point(file_name, output_name):
# 新建一个矢量文件
out_shp = shapefile.Writer(output_name, shapefile.POINT)
out_shp.autoBalance = 1
# 创建字段名称
out_shp.field('TreeID','F',10,8) # string, max-length
out_shp.field('TreeLocationX', 'F', 10, 8) # float
out_shp.field('TreeLocationY', 'F', 10, 8) # float
out_shp.field('TreeHeight','F',10,8) # string, max-length
out_shp.field('CrownDiameter','F',10,8)
out_shp.field('CrownArea','F',10,8) # string, max-length
counter = 1
with codecs.open(file_name, 'rb', 'utf-8') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
# 跳过首行
next(reader, None)
for row in reader:
try:
TreeID = int(row[0])
x_loc = float(row[1])
y_loc = float(row[2])
height = float(row[3])
diameter = float(row[4])
area = float(row[5])
out_shp.point(x_loc, y_loc)
out_shp.record(TreeID, x_loc, y_loc, height, diameter, area)
counter = counter + 1
except:
print('error')
print(row)
def getFileName(path):
# 获取指定目录下的指定后缀的文件名
f_list = os.listdir(path)
out_list = []
for i in f_list:
if os.path.splitext(i)[1]=='.csv':
out_list.append(i)
return out_list
if __name__ == '__main__':
root_dir = 'E:/Dataset/NEON/process/1/'
csv_list = getFileName(root_dir)
for name in csv_list:
pth = os.path.join(root_dir,name)
out_name = name+'_point.shp'
out = root_dir+'/point_shp'
out_pth = os.path.join(out,out_name)
trans_point(pth, out_pth)
上一篇: Util
下一篇: 用于转换Sql的一个小工具