【问题标题】:How to create and return a Zarr file from xarray Dataset?如何从 xarray 数据集创建和返回 Zarr 文件?
【发布时间】:2023-01-04 05:45:29
【问题描述】:

我将如何从 xarray 数据集中创建和返回文件 new_zarr.zarr

我知道 xarray.Dataset.to_zarr() 存在,但这会返回一个 ZarrStore,我必须返回一个 bytes-like 对象。

我已经尝试使用 tempfile 模块但不确定如何继续,我如何将 xarray.Dataset 写入 bytes-like object 以重新生成可以下载的 .zarr 文件?

【问题讨论】:

    标签: python file geospatial python-xarray zarr


    【解决方案1】:

    Zarr 支持多个storage backends(DirectoryStore、ZipStore 等)。如果您正在寻找单个文件对象,那么听起来 ZipStore 就是您想要的。

    import xarray as xr
    import zarr
    
    ds = xr.tutorial.open_dataset('air_temperature')
    store = zarr.storage.ZipStore('./new_zarr.zip')
    ds.to_zarr(store)
    

    可以将 zip 文件视为单个文件 zarr 存储并可以下载(或作为单个存储四处移动)。


    更新 1

    如果你想在内存中完成这一切,你可以扩展 zarr.ZipStore 以允许传入一个 BytesIO 对象:

    class MyZipStore(zarr.ZipStore):
        
        def __init__(self, path, compression=zipfile.ZIP_STORED, allowZip64=True, mode='a',
                     dimension_separator=None):
    
            # store properties
            if isinstance(path, str):  # this is the only change needed to make this work
                path = os.path.abspath(path)
            self.path = path
            self.compression = compression
            self.allowZip64 = allowZip64
            self.mode = mode
            self._dimension_separator = dimension_separator
    
            # Current understanding is that zipfile module in stdlib is not thread-safe,
            # and so locking is required for both read and write. However, this has not
            # been investigated in detail, perhaps no lock is needed if mode='r'.
            self.mutex = RLock()
    
            # open zip file
            self.zf = zipfile.ZipFile(path, mode=mode, compression=compression,
                                      allowZip64=allowZip64)
    

    然后你可以在内存中创建 zip 文件:

    zip_buffer = io.BytesIO()
    
    store = MyZipStore(zip_buffer)
    
    ds.to_zarr(store)
    

    您会注意到 zip_buffer 包含一个有效的 zip 文件:

    zip_buffer.read(10)
    b'PK
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2022-10-08
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多