说明
关于使用 Python 读写 ShapeFile 文件,我的另一篇博客做了简单介绍并用示范了 GDAL库
的简单使用方法。
- Python读写修改Shapefile
https://blog.csdn.net/ShyLoneGirl/article/details/115772352
而实际情况下很多需求并没那么复杂,可能仅仅是对属性表简单地处理,这样的话用 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')
桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_ 桃花仙人种桃树_又摘桃花换酒钱_
.
.
.
.
.
.
桃花仙人种桃树,又摘桃花换酒钱_