jskattt797
jskattt797

Reputation: 271

Get name of an hdf5 group using pytables

import tables
f = tables.open_file('my_file.hdf5', mode='w')
f.create_group(f.root, name='videos')

I have another script that adds data to the 'videos' group. This script checks that the 'videos' group already exists; if 'videos' does not yet exist, the script will create a 'videos' group.

How can I check if a group already exists? I tried using f.walk_groups() and f.root._v_groups, but these don't seem like the best solution. And how can I get a list containing the names (as strings) of all the groups in f.root?

Upvotes: 1

Views: 450

Answers (1)

kcw78
kcw78

Reputation: 8046

All you need to do is check for the existence of the group/dataset path name in the root group. This will return True/False: '/videos' in f.root
So you can create a if block like this:

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

Here's a short code segment that creates a group + 2 array datasets, then prints the logical tests for the group and 2 datasets. Note that arr3 does not exist.

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)

Output will be:

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

Upvotes: 1

Related Questions