如何在h5py文件中列出数据集?

mat*_*ang 11 h5py

我有一个存储numpy数组的h5py文件,但是Object doesn't exist error当我尝试使用我记得的数据集名称打开它时,我有一种方法可以列出文件的数据集吗?

   with h5py.File('result.h5','r') as hf:
        #How can I list all dataset I have saved in hf?
Run Code Online (Sandbox Code Playgroud)

Seb*_*Seb 12

其他答案只是告诉您如何制作根组下的键列表,这些键可能会引用其他组或数据集。

如果你想要更接近 h5dump 但在 python 中的东西,你可以这样做:

import h5py

def descend_obj(obj,sep='\t'):
    """
    Iterate through groups in a HDF5 file and prints the groups and datasets names and datasets attributes
    """
    if type(obj) in [h5py._hl.group.Group,h5py._hl.files.File]:
        for key in obj.keys():
            print sep,'-',key,':',obj[key]
            descend_obj(obj[key],sep=sep+'\t')
    elif type(obj)==h5py._hl.dataset.Dataset:
        for key in obj.attrs.keys():
            print sep+'\t','-',key,':',obj.attrs[key]

def h5dump(path,group='/'):
    """
    print HDF5 file metadata

    group: you can give a specific group, defaults to the root group
    """
    with h5py.File(path,'r') as f:
         descend_obj(f[group])
Run Code Online (Sandbox Code Playgroud)


Ass*_*saf 9

由于使用该keys()函数只会为您提供顶级键,并且还将包含组名称以及数据集(正如Seb已经指出的那样),因此您应该使用该visit()函数(如jasondet建议的那样)并仅保留指向数据集的键。

这个答案是jasondetSeb的答案的合并,对一个简单的函数进行了处理:

def get_dataset_keys(f):
    keys = []
    f.visit(lambda key : keys.append(key) if isinstance(f[key], h5py.Dataset) else None)
    return keys
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 7

如果要列出键名,则需要使用keys()方法为您提供键对象,然后使用list()方法列出键:

with h5py.File('result.h5','r') as hf:
    dataset_names = list(hf.keys())
Run Code Online (Sandbox Code Playgroud)


max*_*111 6

您必须使用keys方法。这将为您提供数据集和组名称的Unicode字符串列表。例如:

Datasetnames=hf.keys()
Run Code Online (Sandbox Code Playgroud)

另一种基于gui的方法是使用HDFView。 https://support.hdfgroup.org/products/java/release/download.html


jas*_*det 6

如果您在命令行,请使用h5ls -r [file]h5dump -n [file]按照其他人的建议。

在 python 中,如果你想在最上面的组下面列出但你不想编写自己的代码来下降树,请尝试访问()函数:

with h5py.File('result.h5','r') as hf:
    hf.visit(print)
Run Code Online (Sandbox Code Playgroud)

或者对于更高级的东西(例如包含属性信息),请使用visititems:

def printall(name, obj):
    print(name, dict(obj.attrs))

with h5py.File('result.h5','r') as hf:
    hf.visititems(printall)
Run Code Online (Sandbox Code Playgroud)