【问题标题】:How to list all datasets in h5py file?如何列出 h5py 文件中的所有数据集?
【发布时间】:2017-12-06 13:56:40
【问题描述】:

我有一个存储 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?

【问题讨论】:

标签: h5py


【解决方案1】:

由于使用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

【讨论】:

  • 这完全用非常简洁的代码解决了我的问题 :) 我猜isinstance(f[key], h5py.Dataset) 可能会更好,以防f[key] 是从h5py.Dataset 继承的类的实例,尽管这可能很少发生.
  • @ajz34 你完全正确,我根据你的建议修改了我的答案,谢谢:)
【解决方案2】:

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

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

with h5py.File('result.h5','r') as hf:
    hf.visit(print)

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

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

with h5py.File('result.h5','r') as hf:
    hf.visititems(printall)

【讨论】:

    【解决方案3】:

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

    如果你想要更接近 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])
    

    【讨论】:

      【解决方案4】:

      只是为了显示底层数据集的名称,我会简单地使用h5dump -n <filename>

      即无需运行 python 脚本。

      【讨论】:

        【解决方案5】:

        如果你想列出键名,你需要使用给你一个键对象的keys()方法,然后使用list()方法列出键:

        with h5py.File('result.h5','r') as hf:
            dataset_names = list(hf.keys())
        

        【讨论】:

          【解决方案6】:

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

          Datasetnames=hf.keys()
          

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-01-05
            • 2015-04-17
            • 2016-01-10
            • 2022-11-14
            • 2020-11-28
            • 1970-01-01
            • 2021-11-25
            相关资源
            最近更新 更多