python将txt点数据转为shape

2021-04-25  本文已影响0人  子皙丶

1. 数据准备

点数据.png

2. 安装python库 gdal

import ogr
from osgeo import osr

3. 代码实现

import ogr
from osgeo import osr
import os

# 如果报错gdal_data未找到,那就需要在环境变量中配置下,然后打印看看位置对不
gdal_data = os.environ['GDAL_DATA']
print(gdal_data)

# 生成的shape位置
shp_path = r'C:\Users\user\Desktop\shp\test.shp'
# 读取的点数据的位置
txt_path = r'C:\Users\user\Desktop\shp\point.txt'

# 选择shape的类型,选择esri的shape格式
driver = ogr.GetDriverByName('ESRI Shapefile')
if os.path.exists(shp_path):
    driver.DeleteDataSource(shp_path)
ds = driver.CreateDataSource(shp_path)
print(ds)

#设置投影
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
print(srs)

# 创建一个图层test,创建三个字段加载到图层
lyr = ds.CreateLayer('test', srs, ogr.wkbPoint)
lon_field = ogr.FieldDefn('lon',ogr.OFTReal)
lat_field = ogr.FieldDefn('lat',ogr.OFTReal)
z_field = ogr.FieldDefn('z',ogr.OFTReal)
lyr.CreateField(lon_field)
lyr.CreateField(lat_field)
lyr.CreateField(z_field)

# 读取点数据
txtRead = open(txt_path, 'r')
while True:
    line = txtRead.readline()
    if not line:
        break
    content = line.split()
    lat = float(content[0])
    lon = float(content[1])
    z = float(content[2])
    #创建几何点
    point = ogr.Geometry(ogr.wkbPoint)
    point.AddPoint(lon, lat)
    #将几何点添加到图层上
    featureDefn = lyr.GetLayerDefn()
    feature = ogr.Feature(featureDefn)
    feature.SetGeometry(point)
    feature.SetField('lon', lon)
    feature.SetField('lat', lat)
    feature.SetField('z',z)
    lyr.CreateFeature(feature)
    feature = None
lyr = None
ds = None

srs.MorphToESRI()
srsfile = open('test.prj', 'w')
srsfile.write(srs.ExportToWkt())
srsfile.close()

4. 可能遇到的问题

如果系统报错说找不到gdal_data这个东西,那就是缺少数据包,下载一个数据包,解压到gdal目录下即可(我是anaconda安装的gdal,所以是这个目录,用pip直接装的话,可以去python包管理中找gdal)
gata-data包地址链接:https://pan.baidu.com/s/1D_3m9vRGrzysrTHJe_MF1w
提取码:s9a7

gata-data.png 配置.png
上一篇下一篇

猜你喜欢

热点阅读