使用 pyshp 直接从 ZIP 读取 Shapefile
问题
你有一个包含单个 ESRI shapefile 数据库(即三个文件)的 ZIP 文件,例如 Natural Earth Countries 数据库。不解压 ZIP 你想使用 pyshp 读取 shapefile 中包含的数据。
解决方案
此解决方案目前仅适用于我的 fork的正确分支。我已提交拉取请求,一旦合并和发布,我将更新此文章。
事实证明,查找 shapefile 的前缀比实际读取 shapefile 更复杂(就代码行数而言)。幸运的是,UliEngineering 提供 find_datasets_by_extension() 和 read_from_zip() 使此过程更易于使用。
read_shapefile_from_zip.py
from UliEngineering.Utils.Files import *
from UliEngineering.Utils.ZIP import *
import shapefile
# 列出 ZIP 内的文件
zipcontents = list(list_zip("ne_110m_admin_0_countries.zip"))
# 查找一个具有 ".shp"、".dbf" 和 ".prj" 扩展名的文件名
dataset_filenames = list(find_datasets_by_extension(zipcontents, (".shp", ".dbf", ".prj")))
# 读取文件(复制到内存)
dataset = read_from_zip("ne_110m_admin_0_countries.zip", dataset_filenames[0])
# 读取 shapefile 格式
reader = shapefile.Reader(shp=dataset[0], dbf=dataset[1], prj=dataset[2])
# 用 reader 做一些有用的事情Check out similar posts by category:
Geoinformatics
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow