How to check if a Group path is valid?


#1

Hi

I’m working on hdf5 files having group and subgroups, so I’m providing the path to get datasets in a group for example. In practise, I know how to check if a group and/or a dataset exists using “.keys()”, but is it possible to check the path itself?

The best solution may be using exceptions based on “KeyErrors” , but I’m wondering if there’s another way?

Thanks

Paul

Blockquote
KeyError: “Unable to open object (object ‘MyPath’ doesn’t exist)”
Blockquote


#2

You can check with the in operator:

f = h5py.File('test.h5')
if 'foo/bar' in f:
    ...

This is documented as __contains__. There are also shortcuts for when you want to create a group or a dataset unless it already exists: require_group() and require_dataset().


#3

Thanks for the answer; I knew how to test a group of a dataset, or how to get a list of groups or datasets, (with .keys()) but I didn’t have the idea to test the path itself (it’s so basic :sweat_smile:)
Thanks