2

想象一下,我正在处理 geopandas 中的 shapefile。然后我想使用另一个库(如networkx)加载它,但由于我的文件很大,我不想保存并重新加载它。有没有办法可以将它保存在内存中?我想它看起来像这样:

import geopandas 
from io import BytesIO 

writeBytes = BytesIO()
### load the demo
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
### do something trivial to the demo
world['geometry'] = world['geometry'].buffer(0.05)
### save to bytes IO so that I can do something else with it without having to save and read a file 
world.to_file(writeBytes)

运行上面会产生一个 TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO 这是完整的回溯:

            TypeError                                 Traceback (most recent call last)
            <ipython-input-1-1ba22f23181a> in <module>
                  8 world['geometry'] = world['geometry'].buffer(0.05)
                  9 ### save to bytes IO so that I can do something else with it without having to save and read a file                                                                                           
            ---> 10 world.to_file(writeBytes)

            ~/.conda/envs/geopandas/lib/python3.7/site-packages/geopandas/geodataframe.py in to_file(self, filename, driver, schema, **kwargs)
                427         """
                428         from geopandas.io.file import to_file
            --> 429         to_file(self, filename, driver, schema, **kwargs)
                430 
                431     def to_crs(self, crs=None, epsg=None, inplace=False):

            ~/.conda/envs/geopandas/lib/python3.7/site-packages/geopandas/io/file.py in to_file(df, filename, driver, schema, **kwargs)
                125     if schema is None:
                126         schema = infer_schema(df)
            --> 127     filename = os.path.abspath(os.path.expanduser(filename))
                128     with fiona_env():
                129         with fiona.open(filename, 'w', driver=driver, crs=df.crs,

            ~/.conda/envs/geopandas/lib/python3.7/posixpath.py in expanduser(path)
                233     """Expand ~ and ~user constructions.  If user or $HOME is unknown,
                234     do nothing."""
            --> 235     path = os.fspath(path)
                236     if isinstance(path, bytes):
                237         tilde = b'~'

任何帮助表示赞赏,谢谢

4

1 回答 1

0

geopandas.to_file() 需要文件路径,而不是 BytesIO 对象。

使用临时文件(或形状文件的文件夹)例如:https ://stackoverflow.com/a/70254174/2023941

于 2021-12-07T02:27:30.460 回答