Python实现csv文件转换为shapefile文件(最简便方法)

Python实现csv文件转换为shapefile文件(最简便方法)

python使用ogr实现csv转shapefile文件

使用python实现csv转化为shapefile文件的方法有很多,我大致看了下csdn的博主们的分享 ,大部分使用了csv库和shapefile库进行csv文件的读取和shapefile文件的写入,我觉得还是略过于复杂了,这里我提供一个最为简便的方法实现csv文件转换为shapefile文件。

'''
Created on 2020年2月6日
@author: Sun Strong
'''
#coding:utf-8
from osgeo import ogr,osr#osr用于获取坐标系统,ogr用于处理矢量文件
import os
path=r"C:\Users\Sun Strong\Desktop\动物跟踪\Galapagos Albatrosses.csv"
os.chdir(os.path.dirname(path))#将path所在的目录设置为当前文件夹
shp_fn="Animal_shp.shp"#即将转化为的shapefile文件名
ds=ogr.Open(path,1)#1代表可读可写,默认为0
csv_lyr=ds.GetLayer()#获取csv文件
sr=osr.SpatialReference()
sr.ImportFromEPSG(4326)#定义坐标系统
shp_driver=ogr.GetDriverByName('ESRI Shapefile')#获取shapefile文件处理句柄
if os.path.exists(shp_fn):#如果文件夹中已存在同名文件则先删除
    shp_driver.DeleteDataSource(shp_fn)
shp_ds=shp_driver.CreateDataSource(shp_fn)
Animal_lyr=shp_ds.CreateLayer(shp_fn,sr,ogr.wkbPoint)#创建一个点图层
tag_id=ogr.FieldDefn('tag_id',ogr.OFTString)#为点图层创建字段
timestamp=ogr.FieldDefn('timestamp',ogr.OFTString)
Animal_lyr.CreateField(tag_id)
Animal_lyr.CreateField(timestamp)
for csv_row in csv_lyr:#对于csv文件中每一行
    point_feature=ogr.Feature(Animal_lyr.GetLayerDefn())#创建一个点
    x=csv_row.GetFieldAsDouble('location-long')#x坐标
    y=csv_row.GetFieldAsDouble('location-lat')#y坐标
    shp_pt=ogr.Geometry(ogr.wkbPoint)#创建几何点
    shp_pt.AddPoint(x,y)
    #获取字段值,并写入到该点中
    tag_value=csv_row.GetFieldAsString('individual-local-identifier')
    timestamp_value=csv_row.GetFieldAsString('timestamp')
    point_feature.SetField('tag_id',tag_value)
    point_feature.SetField('timestamp',timestamp_value)
    point_feature.SetGeometry(shp_pt)#将点的几何数据添加到点中
    Animal_lyr.CreateFeature(point_feature)#将点写入到图层中
del ds
del shp_ds#释放句柄,文件缓冲到磁盘
print("This process has succeeded!")
  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值