使用 python 库 h5py 获取 h5 文件中的所有键及其层次结构

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

有什么方法可以使用 python 库 h5py 递归地获取 h5 文件中的所有密钥?我尝试使用下面的代码

import h5py

h5_data = h5py.File(h5_file_location, 'r')
print(h5_data.keys())

但它只打印 h5 文件的顶级键。

您可能想要遍历键以 return 它们的值。下面是一个简单的函数。

import h5py

h5_file_location = '../../..'
h5_data = h5py.File(h5_file_location, 'r')

def keys(f):
    return [key for key in f.keys()]
print(keys(h5_data))

keys() 对组返回的一些键可能是数据集,有些可能是子组。为了找到 all 键,您需要递归组。这是一个简单的脚本:

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))

给出:

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