问题
How do I traverse all the groups and datasets of an hdf5 file using h5py?
I want to retrieve all the contents of the file from a common root using a for loop or something similar.
回答1:
visit() and visititems() are your friends here. Cf. http://docs.h5py.org/en/latest/high/group.html#Group.visit. Note that an h5py.File is also an h5py.Group. Example (not tested):
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)
回答2:
Well this is kind of an old thread but I thought I'd contribute anyway. This is what I did in a similar situation. For a data structure set up like this:
[group1]
[group2]
dataset1
dataset2
[group3]
dataset3
dataset4
I used:
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)
I haven't found an h5py equivalent for os.walk.
来源:https://stackoverflow.com/questions/31146036/how-do-i-traverse-a-hdf5-file-using-h5py