python中如何使用pyshp读写shp文件

其他教程   发布日期:2025年04月19日   浏览次数:164

本篇内容主要讲解“python中如何使用pyshp读写shp文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python中如何使用pyshp读写shp文件”吧!

    安装

    1. pip install pyshp

    引入

    1. import shapefile

    读取

    sf=shapefile.Reader("{路径名}",encoding='utf-8') # 仅仅读取

    shapes与shape

    shapes=sf.shapes() 返回值是一个列表,包含该文件中所有的”几何数据”对象

    shape=sf.shape(0) Shape是第1个”几何数据”对象

    shapeType返回集合类型

    返回第1个对象的数据类型属性

    1. 几何类型
    2. NULL = 0
    3. POINT = 1
    4. POLYLINE = 3
    5. POLYGON = 5
    6. MULTIPOINT = 8
    7. POINTZ = 11
    8. POLYLINEZ = 13
    9. POLYGONZ = 15
    10. MULTIPOINTZ = 18
    11. POINTM = 21
    12. POLYLINEM = 23
    13. POLYGONM = 25
    14. MULTIPOINTM = 28
    15. MULTIPATCH = 31
    16. print(shape.shapeType)

    bbox 返回数据范围

    shape.bbox 返回第一个集合对象的数据范围(左下角的x,y坐标和右上角的x,y坐标)

    points 所有坐标点

    shape.points 返回第一个集合对象的所有坐标点

    parts 返回’块’的第一个点坐标

    shape.parts 返回第一个对象的每个”块”的第一个点坐标

    records与record

    获取属性列表

    records

    获取属性列表,是个函数

    sf.records();

    返回的值是个list

    record
    获取一条数据

    sf.record(0)
    返回的值是class

    shapeRecords

    同时获取record和shape

    1. # 同时读取geometry and records
    2. sf.shapeRecords()
    3. 获取所有
    4. red=sf.shapeRecords()[0] #获取第一条数据
    5. print(red.record) #获取record
    6. print(red.shape) #获取shape

    fields

    获取shp文件属性字段

    1. print(sf.fields)
    2. [('DeletionFlag', 'C', 1, 0), ['OBJECTID', 'N', 9, 0], ['BSM', 'C', 12, 0], ['PXZQDM', 'C', 2, 0], ['PXZQMC', 'C', 50, 0]]

    写入

    1. import shapefile
    2. outshp = 'a.shp'
    3. landlist=[ '84.60212,45.03658,84.60794,45.03938,84.61473,45.04151,84.62442,45.04375,84.62727,45.03632,84.63939,45.0367,84.64906,45.03277,84.63886,45.02233',
    4. '84.58063,45.05523,84.57974,45.04717,84.59864,45.04792,84.60078,45.05523,84.58758,45.05473,84.58223,45.05523'
    5. ]
    6. def tramform(lat_lng):
    7. str =lat_lng
    8. str = str.split(',')
    9. arr = []
    10. for i in range(len(str) - 1):
    11. # 第一列,第二列作为经纬度(x,y)创建点
    12. if i % 2 == 0:
    13. arr.append([float(str[i]), float(str[i + 1])])
    14. return arr
    15. fileWrite = shapefile.Writer("create/1.shp",encoding='utf-8') # 新建数据存放位置
    16. # shp文件属性字段 Fid,Shape会自动生成。
    17. fileWrite.field('landid')
    18. fileWrite.field('landName')
    19. for i in range(len(landlist)):
    20. # 第一步:塞入形状
    21. ## 这个形状指的就是那些点的集合
    22. ## 由于源码中要求的输入是列表,因此就算只塞入一个,也要套一个列表
    23. arr=[]
    24. arr=tramform(landlist[i])
    25. #[[84.60212, 45.03658], [84.60794, 45.03938], [84.61473, 45.04151], [84.62442, 45.04375], [84.62727, 45.03632], [84.63939, 45.0367], [84.64906, 45.03277], [84.63886, 45.02233]]
    26. #poly 写入面,点线面使用不同函数
    27. fileWrite.poly([arr])
    28. # 第二步:塞入属性值
    29. fileWrite.record(str(i), '地块')
    30. # 保存结束
    31. fileWrite.close()

    以上就是python中如何使用pyshp读写shp文件的详细内容,更多关于python中如何使用pyshp读写shp文件的资料请关注九品源码其它相关文章!