pyshp读取Shapefile方法

27 篇文章 3 订阅
6 篇文章 1 订阅

说明

关于使用 Python 读写 ShapeFile 文件,我的另一篇博客做了简单介绍并用示范了 GDAL库 的简单使用方法。

而实际情况下很多需求并没那么复杂,可能仅仅是对属性表简单地处理,这样的话用 GDAL 就不太合适了:一方面 GDAL 功能过于强大,绝大多数功能用不到,太大材小用了。另一方面 GDAL 的安装未必有想想中的那么顺利(软件版本、与其他软件兼容性等因素造成)。

那么,pyshp 就很合适了。

pyshp安装

直接我就

pip install pyshp

试一下行不行

D:\test>python
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32

>>> import shapefile
>>>     

没有问题

读取shp

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import shapefile

def read_attributes(_filename):
    sf = shapefile.Reader(_filename)
    table_content_list = []
    for item in sf.records():
        table_content_list.append(item.as_dict())
    return table_content_list

def read_table_header(_filename):
    sf = shapefile.Reader(_filename)
    table_header_list = []
    for item in sf.fields:
        table_header_list.append(item[0])
    return table_header_list


if __name__ == '__main__':

    shpFile = 'D://test.shp'
    table_header = read_table_header(shpFile)
    print(table_header)
    table_content = read_attributes(shpFile)
    for row in table_content:
        print(row)

大概这样就行了。

问题解决

如果出现

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 8: invalid continuation byte

可修改其默认编码方式

sf = shapefile.Reader(_filename, encoding='GBK')
桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_

.
.
.
.
.
.


桃花仙人种桃树,又摘桃花换酒钱_

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值