Get all keys and its hierarchy in h5 file using python library h5py

Some of the keys returned by keys() on a Group may be Datasets some may be sub Groups. In order to find all keys you need to recurse the Groups. Here is a simple script to do that:

import h5py

def allkeys(obj):
    "Recursively find all keys in an h5py.Group."
    keys = (obj.name,)
    if isinstance(obj, h5py.Group):
        for key, value in obj.items():
            if isinstance(value, h5py.Group):
                keys = keys + allkeys(value)
            else:
                keys = keys + (value.name,)
    return keys

h5 = h5py.File('/dev/null', 'w')
h5.create_group('g1')
h5.create_group('g2')
h5.create_dataset('d1', (10,), 'i')
h5.create_dataset('d2', (10, 10,), 'f')
h5['g1'].create_group('g1')
h5['g1'].create_dataset('d1', (10,), 'i')
h5['g1'].create_dataset('d2', (10,), 'f')
h5['g1/g1'].attrs['a'] = 'b'
print(allkeys(h5))

Gives:

('/', '/d1', '/d2', '/g1', '/g1/d1', '/g1/d2', '/g1/g1', '/g2')

Tags:

Python

H5Py