python-3.x - Requests.get(zipfile) 获取 'BadZipFile: File is not a zip file"

标签 python-3.x python-requests jupyter-notebook zip geopandas

我正在尝试加载地理文件集的 zipfile 中的 shapefile。我尝试了几种方法并一直在研究,但一无所获。以下代码应该适用于 Python 3.5。

我尝试过 Andrew Gaidus 示例方法,并意识到它适用于之前的 Python 版本。 Oldja 方法来自 Python 3.x 文档,应该可以工作。但问题不断出现。

dls = "https://github.com/ItsMeLarry/Coursera_Capstone/raw/master/tl_2010_25 009_tract00.zip"
print('Downloading shapefile...')
r = requests.get(dls)
z = zipfile.ZipFile(io.BytesIO(r.content))
print("Done")
z.extractall(path='tmp/') # extract to folder
filenames = [y for y in sorted(z.namelist()) for ending in ['dbf', 
'prj', 'shp', 'shx'] if y.endswith(ending)] 
print(filenames)
dbf, prj, shp, shx = [filename for filename in filenames]
print(shp)
lynnmap = gpd.read_file(shp)

我得到了 4 个文件名,就像我应该的那样。现在,在 lynnmap=gpd... 处,我收到错误:

操作系统错误:没有这样的文件或目录:“tl_2010_25009_tract00.shp”。

示例不执行“打开”操作,但我想知道 geopandas 是否告诉我应该这样做。

最佳答案

如果目标只是从 GitHub 读取文件并从中创建一个 GeoDataFrame(并且您不一定希望在本地下载并解压缩它,以便更快地重新读取),您可以直接从使用 geopandas.read_file 函数的 GitHub 网址:

In [4]: df = geopandas.read_file("https://github.com/ItsMeLarry/Coursera_Capstone/raw/master/tl_2010_25009_tract00.zip") 

In [5]: df.head()                                                      
Out[5]: 
  STATEFP00 COUNTYFP00  ...    INTPTLON00                                           geometry
0        25        009  ...  -070.9744124  POLYGON ((-70.977153 42.452525, -70.9773139999...
1        25        009  ...  -070.9789107  POLYGON ((-70.986276 42.46005299999999, -70.98...
2        25        009  ...  -070.9853846  POLYGON ((-70.988809 42.460175, -70.9889149999...
3        25        009  ...  -070.9611517  POLYGON ((-70.95187 42.473647, -70.950974 42.4...
4        25        009  ...  -070.9925246  (POLYGON ((-71.000474 42.507547, -70.999544 42...

[5 rows x 13 columns]

geopandas.read_file 接受一个 url,还可以自动处理不同 shapefile 文件的 zip 文件,并返回一个 GeoDataFrame。

关于python-3.x - Requests.get(zipfile) 获取 'BadZipFile: File is not a zip file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55554688/

相关文章:

python-requests - C# 相当于 requests.post() 函数

python - 是否可以在 Jupyter 笔记本中显示控制台?

python - 如何在python中不使用 "import"导入

python - 如何在请求中定义 HTTP 协议(protocol)版本?

python-3.x - Selenium + Firefox开发版: send_keys throwing [object Undefined] exception

python - 使用请求时的Python错误处理

用于 Jupyter 的 Julia Kernel 崩溃

jupyter-notebook - 如何将参数传递给 PapermillOperator 以在 Airflow 上运行作业?

Python Regex 在 3 个在线测试人员上成功测试,但在代码中不起作用

python - 仅使用 pathlib 规范化不存在的路径