有什么方法可以使用python库h5py递归获取h5文件中的所有键?我尝试使用下面的代码
import h5py
h5_data = h5py.File(h5_file_location, 'r')
print(h5_data.keys())
但是它仅打印h5文件的顶级密钥。
您可能想要遍历键以返回其值。下面是执行此操作的简单函数。
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键,您需要递归Groups。这是执行此操作的简单脚本:
import h5py
def allkeys(obj, keys=[]):
''' Recursively find all keys '''
keys.append(obj.name)
if isinstance(obj, h5py.Group):
for item in obj:
if isinstance(obj[item], h5py.Group):
allkeys(obj[item], keys)
else: # isinstance(obj[item], h5py.Dataset):
keys.append(obj[item].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'].attrs['myPath'] = 'g1'
h5['g1/g1'].attrs['myPath'] = 'g1/g1'
print(allkeys(h5))
Gives:
['/', '/d1', '/d2', '/g1', '/g1/d1', '/g1/d2', '/g1/g1', '/g2']