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