我正在尝试加载地理文件集的 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/