Python零盘处理ZIP提取含Africa的Shapefile转GeoJSON报seek属性缺失错误
任务场景
首次使用Python处理ZIP压缩文件,全程不向磁盘写入任何内容,基于指定网络资源地址http://shapefiles.fews.net.s3.amazonaws.com/ALL_HFIC.zip完成指定操作流程:
- 从目标地址获取ZIP压缩包,所有数据全程存储在内存中
- 从ZIP归档中筛选文件名包含
Africa的shapefile文件 - 将所有匹配的shapefile读取到geopandas中,合并为单个空间数据集
- 将合并后的数据集转换为GeoJSON格式输出
现有代码问题说明
当前代码运行持续抛出报错:AttributeError: 'ZipFile' object has no attribute 'seek',核心问题共三处:
- 重复无效包装:代码前期已经基于内存字节流初始化了压缩包对象
myzipfile,后续with块中引用了从未定义的zip_file变量传入zipfile.ZipFile构造函数做二次解析。ZipFile实例本身不是支持seek操作的可寻址流对象,geopandas底层调用fiona库读取时就会直接抛出上述seek属性错误 - shapefile读取逻辑错误:仅读取单个
.shp后缀文件的二进制内容传给geopandas。shapefile是多文件绑定格式,完整可读的shapefile必须配套同名的.shx(空间索引)、.dbf(属性表)、.prj(投影定义)文件,单独提取shp二进制内容根本无法解析有效空间数据 - 流程违反约束:最后一步
gdf_africa.to_file("output.json", driver="GeoJSON")会将结果写入本地磁盘,不符合全程不写盘的硬性要求
修正后的可运行代码
import io import zipfile import requests import pandas as pd import geopandas as gpd from fiona.io import ZipMemoryFile # 目标资源地址 URL = "http://shapefiles.fews.net.s3.amazonaws.com/ALL_HFIC.zip" # 匹配规则 is_africa_related = lambda filename: "Africa" in filename # 1. 拉取ZIP包到内存,全程不落地 resp = requests.get(URL) zip_bytes = io.BytesIO(resp.content) matched_gdf_list = [] # 2. 从内存ZIP中筛选目标shapefile with zipfile.ZipFile(zip_bytes, 'r') as zf: all_entries = zf.namelist() # 先提取所有匹配的shapefile的基础名(去掉后缀) target_basenames = set() for entry_name in all_entries: if is_africa_related(entry_name) and entry_name.endswith(".shp"): base_name = entry_name.rsplit(".", 1)[0] target_basenames.add(base_name) # 3. 逐组读取shapefile,合并数据集 for base_name in target_basenames: with ZipMemoryFile(zip_bytes) as zip_memory: with zip_memory.open(base_name + ".shp") as src: gdf = gpd.read_file(src) matched_gdf_list.append(gdf) merged_gdf = gpd.GeoDataFrame( pd.concat(matched_gdf_list, ignore_index=True), crs=matched_gdf_list[0].crs ) # 4. 转换为内存中的GeoJSON字符串,不写入本地磁盘 geojson_content = merged_gdf.to_json()
内容的提问来源于stack exchange,提问作者Tytire Recubans
相关产品推荐
相关产品推荐

