Groups are the container mechanism by which HDF5 files are organized. From a Python perspective, they operate somewhat like dictionaries. In this case the “keys” are the names of group members, and the “values” are the members themselves (Group and Dataset) objects.
Group objects also contain most of the machinery which makes HDF5 useful. The File object does double duty as the HDF5 root group, and serves as your entry point into the file:
>>> f = h5py.File('foo.hdf5','w')
>>> f.name
'/'
>>> f.keys()
[]
New groups are easy to create:
>>> grp = f.create_group("bar")
>>> grp.name
'/bar'
>>> subgrp = grp.create_group("baz")
>>> subgrp.name
'/bar/baz'
Datasets are also created by a Group method:
>>> dset = subgrp.create_dataset("MyDS", (100,100), dtype='i')
>>> dset.name
'/bar/baz/MyDS'
Groups implement a subset of the Python dictionary convention. They have methods like keys(), values() and support iteration. Most importantly, they support the indexing syntax, and standard exceptions:
>>> myds = subgrp["MyDS"]
>>> missing = subgrp["missing"]
KeyError: "Name doesn't exist (Symbol table: Object not found)"
Objects can be deleted from the file using the standard syntax:
>>> del subgroup["MyDataset"]
Group objects implement the following subset of the Python “mapping” interface:
When using h5py from Python 3, the keys(), values() and items() methods will return view-like objects instead of lists. These objects support containership testing and iteration, but can’t be sliced like lists.
The iterkeys(), itervalues(), and iteritems() methods are likewise not available in Python 3. You may wish to use the standard conversion script 2to3 which ships with Python to accomodate these changes.
Like a UNIX filesystem, HDF5 groups can contain “soft” or symbolic links, which contain a text path instead of a pointer to the object itself. You can easily create these in h5py:
>>> myfile = h5py.File('foo.hdf5','w')
>>> group = myfile.create_group("somegroup")
>>> myfile["alias"] = h5py.SoftLink('/somegroup')
Once created, soft links act just like regular links. You don’t have to do anything special to access them:
>>> print myfile["alias"]
<HDF5 group "/alias" (0 members)>
However, they “point to” the target:
>>> myfile['alias'] == myfile['somegroup']
True
If the target is removed, they will “dangle”:
>>> del myfile['somegroup']
>>> print myfile['alias']
KeyError: 'Component not found (Symbol table: Object not found)'
Note
The class h5py.SoftLink doesn’t actually do anything by itself; it only serves as an indication to the Group object that you want to create a soft link.
New in HDF5 1.8, external links are “soft links plus”, which allow you to specify the name of the file as well as the path to the desired object. You can refer to objects in any file you wish. Use similar syntax as for soft links:
>>> myfile = h5py.File('foo.hdf5','w')
>>> myfile['ext link'] = h5py.ExternalLink("otherfile.hdf5", "/path/to/resource")
When the link is accessed, the file “otherfile.hdf5” is opened, and object at “/path/to/resource” is returned.
Note
Since the object retrieved is in a different file, its ”.file” and ”.parent” properties will refer to objects in that file, not the file in which the link resides.
Although soft and external links are designed to be transparent, there are some cases where it is valuable to know when they are in use. The Group method “get” takes keyword arguments which let you choose whether to follow a link or not, and to return the class of link in use (soft or external).
Represents an HDF5 group.
``Group`` methods
Add an object to the group. The name must not already be in use.
The action taken depends on the type of object assigned:
Open an object in the file
Create and return a new subgroup.
Name may be absolute or relative. Fails if the target name already exists.
Create a new HDF5 dataset
Keyword-only arguments:
Return a group, creating it if it doesn’t exist.
TypeError is raised if something with that name already exists that isn’t a group.
Open a dataset, creating it if it doesn’t exist.
If keyword “exact” is False (default), an existing dataset must have the same shape and a conversion-compatible dtype to be returned. If True, the shape and dtype must match exactly.
Other dataset keywords (see create_dataset) may be provided, but are only used if a new dataset is to be created.
Raises TypeError if an incompatible object already exists, or if the shape or dtype don’t match according to the above rules.
Copy an object or group.
The source can be a path, Group, Dataset, or Datatype object. The destination can be either a path or a Group object. The source and destinations need not be in the same file.
If the source is a Group object, all objects contained in that group will be copied recursively.
When the destination is a Group object, by default the target will be created in that group with its current name (basename of obj.name). You can override that by setting “name” to a string.
Example:
>>> f = File('myfile.hdf5')
>>> f.listnames()
['MyGroup']
>>> f.copy('MyGroup', 'MyCopy')
>>> f.listnames()
['MyGroup', 'MyCopy']
Recursively visit all names in this group and subgroups (HDF5 1.8).
You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:
func(<member name>) => <None or return value>
Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. No particular order of iteration within groups is guranteed.
Example:
>>> # List the entire contents of the file
>>> f = File("foo.hdf5")
>>> list_of_names = []
>>> f.visit(list_of_names.append)
Recursively visit names and objects in this group (HDF5 1.8).
You supply a callable (function, method or callable object); it will be called exactly once for each link in this group and every group below it. Your callable must conform to the signature:
func(<member name>, <object>) => <None or return value>
Returning None continues iteration, returning anything else stops and immediately returns that value from the visit method. No particular order of iteration within groups is guranteed.
Example:
# Get a list of all datasets in the file >>> mylist = [] >>> def func(name, obj): ... if isinstance(obj, Dataset): ... mylist.append(name) ... >>> f = File(‘foo.hdf5’) >>> f.visititems(func)
Dictionary-like methods
Get a list containing member names
Get a list containing member objects
Get a list of tuples containing (name, object) pairs
Get an iterator over member names
Get an iterator over member objects
Get an iterator over (name, object) pairs
Retrieve an item or other information.
Example:
>>> cls = group.get('foo', getclass=True)
>>> if cls == SoftLink:
... print '"foo" is a soft link!'
Properties common to all HDF5 objects:
Return a File instance associated with this object
Return the parent group of this object.
This is always equivalent to obj.file[posixpath.dirname(obj.name)]. ValueError if this object is anonymous.
Return the full name of this object. None if anonymous.
Low-level identifier appropriate for this object
An (opaque) HDF5 reference to this object
Attributes attached to this object