Skip to content

Instantly share code, notes, and snippets.

@yarikoptic
Created November 26, 2025 15:54
Show Gist options
  • Select an option

  • Save yarikoptic/964252fa188ae0257e5fa8f0b9e119f0 to your computer and use it in GitHub Desktop.

Select an option

Save yarikoptic/964252fa188ae0257e5fa8f0b9e119f0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "pynwb>=2.8.0",
# "hdmf-zarr>=0.8.0",
# ]
# ///
"""Convert NWB file from HDF5 to Zarr format."""
import sys
from pathlib import Path
from hdmf_zarr import NWBZarrIO
from pynwb import NWBHDF5IO
def nwb_to_zarr(input_path: str | Path, output_path: str | Path | None = None) -> Path:
"""
Convert an HDF5 NWB file to Zarr format.
Parameters
----------
input_path : str | Path
Path to input .nwb (HDF5) file
output_path : str | Path | None
Path for output .zarr directory. If None, uses input name with .zarr extension
Returns
-------
Path
Path to the created Zarr store
"""
input_path = Path(input_path)
if output_path is None:
output_path = input_path.with_suffix(".zarr")
output_path = Path(output_path)
# Read the HDF5 NWB file
with NWBHDF5IO(input_path, mode="r", load_namespaces=True) as read_io:
nwbfile = read_io.read()
# Export to Zarr
with NWBZarrIO(output_path, mode="w") as export_io:
export_io.export(src_io=read_io, nwbfile=nwbfile, write_args={'link_data': False})
print(f"Converted: {input_path} -> {output_path}")
return output_path
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <input.nwb> [output.zarr]", file=sys.stderr)
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2] if len(sys.argv) > 2 else None
nwb_to_zarr(input_file, output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment