如何用h5py区分HDF5数据集和组?

Tri*_*ion 15 python hdf5 h5py

我使用Python包h5py(版本2.5.0)来访问我的hdf5文件.

我想遍历文件的内容并对每个数据集执行某些操作.

使用visit方法:

import h5py

def print_it(name):
    dset = f[name]
    print(dset)
    print(type(dset))


with h5py.File('test.hdf5', 'r') as f:
    f.visit(print_it)
Run Code Online (Sandbox Code Playgroud)

对于我获得的测试文件:

<HDF5 group "/x" (1 members)>
<class 'h5py._hl.group.Group'>
<HDF5 dataset "y": shape (100, 100, 100), type "<f8">
<class 'h5py._hl.dataset.Dataset'>
Run Code Online (Sandbox Code Playgroud)

这告诉我文件中有一个数据集和一个组.然而,除了用于type()区分数据集和组之外,没有明显的方法.遗憾的是,h5py文档没有说明这个主题.他们总是假设您事先知道什么是组以及数据集是什么,例如因为他们自己创建了数据集.

我希望有类似的东西:

f = h5py.File(..)
for key in f.keys():
    x = f[key]
    print(x.is_group(), x.is_dataset()) # does not exist
Run Code Online (Sandbox Code Playgroud)

在使用h5py读取Python中的未知hdf5文件时,如何区分组和数据集?如何获取所有链接中所有组的所有数据集的列表?

Gal*_*all 13

不幸的是,在h5py api中没有内置的方法来检查这个,但你可以简单地检查一下项目的类型is_dataset = isinstance(item, h5py.Dataset).

要列出文件的所有内容(但文件的属性除外),您可以使用Group.visititems带有项目名称和实例的callable.


Tri*_*ion 7

尽管Gall和James Smith的回答总体上表明了解决方案,但仍需要通过分层HDF结构遍历和对所有数据集进行过滤。我使用的yield from是Python 3.3+中提供的工具,它工作得很好,并在此处展示。

import h5py

def h5py_dataset_iterator(g, prefix=''):
    for key in g.keys():
        item = g[key]
        path = '{}/{}'.format(prefix, key)
        if isinstance(item, h5py.Dataset): # test for dataset
            yield (path, item)
        elif isinstance(item, h5py.Group): # test for group (go down)
            yield from h5py_dataset_iterator(item, path)

with h5py.File('test.hdf5', 'r') as f:
    for (path, dset) in h5py_dataset_iterator(f):
        print(path, dset)
Run Code Online (Sandbox Code Playgroud)