Skip to content

Instantly share code, notes, and snippets.

@bendichter
Last active March 23, 2022 00:54
Show Gist options
  • Save bendichter/8f605d6d3e5a7b11a00255278aa2d5f9 to your computer and use it in GitHub Desktop.
Save bendichter/8f605d6d3e5a7b11a00255278aa2d5f9 to your computer and use it in GitHub Desktop.
draw tree structure of h5py File
import h5py
def print_group(group: h5py.Group):
name = group.name.split('/')[-1]
return f"{name} ({len(group.keys())} objects)/"
def print_dataset(dataset: h5py.Dataset):
name = dataset.name.split('/')[-1]
return f"{name} {dataset.shape}, {dataset.dtype}"
def print_line(elem, last, op):
if op:
op[0] = False
line = ""
for o in op:
if o:
line += "| "
else:
line += " "
if last:
line += "└── "
else:
line += "├── "
if isinstance(elem, h5py.Group):
line += print_group(elem)
elif isinstance(elem, h5py.Dataset):
line += print_dataset(elem)
return line
def _show_group(group, last=True, op = []):
out = []
out.append(print_line(group, last, op))
for i, key in enumerate(group.keys()):
elem = group[key]
this_last = i == (len(group.keys()) - 1)
if isinstance(elem, h5py.Group):
out.extend(_show_group(elem, this_last, op + [True]))
if isinstance(elem, h5py.Dataset):
out.append(print_line(elem, this_last, op + [not last]))
return out
def file_tree(groups):
return '\n'.join(_show_group(file))
@bendichter
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment