如何使用h5py遍历hdf5文件的所有组和数据集?
我想使用for循环或类似东西从公共根目录检索文件的所有内容。
答案 0 :(得分:10)
visit()
和visititems()
是您的朋友。参看http://docs.h5py.org/en/latest/high/group.html#Group.visit。请注意,h5py.File
也是h5py.Group
。示例(未测试):
def visitor_func(name, node):
if isinstance(node, h5py.Dataset):
# node is a dataset
else:
# node is a group
with h5py.File('myfile.h5', 'r') as f:
f.visititems(visitor_func)
答案 1 :(得分:1)
这是一个非常老的线程,但是我找到了一种在Python中基本上复制h5ls命令的解决方案:
class H5ls:
def __init__(self):
# Store an empty list for dataset names
self.names = []
def __call__(self, name, h5obj):
# only h5py datasets have dtype attribute, so we can search on this
if hasattr(h5obj,'dtype') and not name in self.names:
self.names += [names]
# we have no return so that the visit function is recursive
if __name__ == "__main__":
df = h5py.File(filename,'r')
h5ls = H5ls()
# this will now visit all objects inside the hdf5 file and store datasets in h5ls.names
df.visititems(h5ls)
df.close()
此代码将遍历整个HDF5文件,并将所有数据集存储在h5ls.names
中,希望对您有所帮助!
答案 2 :(得分:0)
嗯,这是一个古老的线索,但我认为无论如何我都会做出贡献。这就是我在类似情况下所做的。 对于这样设置的数据结构:
[group1]
[group2]
dataset1
dataset2
[group3]
dataset3
dataset4
我用过:
datalist = []
def returnname(name):
if 'dataset' in name and name not in datalist:
return name
else:
return None
looper = 1
while looper == 1:
name = f[group1].visit(returnname)
if name == None:
looper = 0
continue
datalist.append(name)
我还没有找到os.walk的h5py等价物。