【问题标题】:Get name of an hdf5 group using pytables使用 pytables 获取 hdf5 组的名称
【发布时间】:2021-03-27 08:42:41
【问题描述】:
import tables
f = tables.open_file('my_file.hdf5', mode='w')
f.create_group(f.root, name='videos')

我有另一个将数据添加到“视频”组的脚本。此脚本检查“视频”组是否已存在;如果 'videos' 尚不存在,脚本将创建一个 'videos' 组。

如何检查组是否已存在?我尝试使用 f.walk_groups() 和 f.root._v_groups,但这些似乎不是最好的解决方案。以及如何获取包含 f.root 中所有组的名称(作为字符串)的列表?

【问题讨论】:

    标签: hdf5 pytables


    【解决方案1】:

    您需要做的就是检查根组中是否存在组/数据集路径名。这将返回 True/False:'/videos' in f.root
    所以你可以像这样创建一个if 块:

    if '/videos' in f.root:
        do something
    

    这是一个简短的代码段,它创建一个组 + 2 个数组数据集,然后打印组和 2 个数据集的逻辑测试。请注意,arr3 不存在。

    import tables as tb
    import numpy as np
    
    with tb.File('SO_65327481.hdf5', mode='w') as h5f:
        h5f.create_group('/', name='videos')
        arr = np.random.random((10,10))
        h5f.create_array('/videos',name='arr1', obj=arr)
        arr = np.random.random((10,10))
        h5f.create_array('/videos','arr2',obj=arr)
    
        print ( 'videos exists:', '/videos' in h5f.root)
        print ( 'arr2 exists:', '/videos/arr2' in h5f.root)
        print ( 'arr3 exists:', '/videos/arr3' in h5f.root)
    

    输出将是:

    videos exists: True
    arr2 exists: True
    arr3 exists: False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-04
      • 2019-06-15
      • 2021-11-14
      • 2017-11-21
      • 2016-11-12
      • 2020-04-27
      • 2012-04-03
      • 2012-12-17
      相关资源
      最近更新 更多