我如何使用h5py遍历hdf5文件中的所有组和数据集?
我想要使用for循环或类似的方法从共同的根目录检索文件的所有内容。
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)
这是一个相当老的帖子,但我找到了一种基本上复制h5ls命令在Python中的解决方案:
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()
h5ls.names
中,希望这能有所帮助!+= [names]
更改为 += [name]
。 - Alex Lenail虽然这个帖子有点旧,但我还是想做出贡献。在类似的情况下,我做了以下操作。 对于像这样设置的数据结构:
[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。
visitor_func
)返回一个非“None”值,那么循环将终止。 - DilithiumMatrix