我使用package 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)对于测试文件,我获得:
<HDF5 group "/x" (1 members)>
<class 'h5py._hl.group.Group'>
<HDF5 dataset "y": shape (100, 100, 100), type "<f8">
<class 'h5py._hl.dataset.Dataset'>这告诉我,文件中有一个数据集和一个组。然而,除了使用type()来区分数据集和组之外,没有明显的方法。不幸的是,h5py文档没有提到这个话题。他们总是假设您事先知道什么是组,什么是数据集,例如,因为他们自己创建了数据集。
我想要这样的东西:
f = h5py.File(..)
for key in f.keys():
x = f[key]
print(x.is_group(), x.is_dataset()) # does not exist在使用hdf5读取h5py中未知的h5py文件时,如何区分组和数据集?如何获得所有数据集、所有组、所有链接的列表?
发布于 2015-12-17 09:09:25
不幸的是,h5py api中没有内置的方法来检查这一点,但是您可以简单地用is_dataset = isinstance(item, h5py.Dataset)检查项目的类型。
要列出文件的所有内容(但文件的属性除外),可以使用Group.visititems与可调用的文件一起使用,该调用接受项的名称和实例。
发布于 2015-12-21 17:14:32
虽然Gall和James的回答表明了总体上的解决方案,但仍然需要对所有数据集进行分层HDF结构的遍历和过滤。我使用的是yield from,它在Python 3.3+中是可用的,它运行得很好,并在这里展示。
import h5py
def h5py_dataset_iterator(g, prefix=''):
for key, item in g.items():
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)发布于 2018-10-23 07:23:41
例如,如果要打印HDF5文件的结构,可以使用以下代码:
def h5printR(item, leading = ''):
for key in item:
if isinstance(item[key], h5py.Dataset):
print(leading + key + ': ' + str(item[key].shape))
else:
print(leading + key)
h5printR(item[key], leading + ' ')
# Print structure of a `.h5` file
def h5print(filename):
with h5py.File(filename, 'r') as h:
print(filename)
h5printR(h, ' ')示例
>>> h5print('/path/to/file.h5')
file.h5
test
repeats
cell01: (2, 300)
cell02: (2, 300)
cell03: (2, 300)
cell04: (2, 300)
cell05: (2, 300)
response
firing_rate_10ms: (28, 30011)
stimulus: (300, 50, 50)
time: (300,)https://stackoverflow.com/questions/34330283
复制相似问题