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:
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.
It’s recommended to use the Group/File method create_group to create these objects, rather than trying to create them yourself.
Groups implement a basic dictionary-style interface, supporting __getitem__, __setitem__, __len__, __contains__, keys(), values() and others.
They also contain the necessary methods for creating new groups and datasets. Group attributes can be accessed via <group>.attrs.
``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:
Create and return a new dataset. Fails if “name” already exists.
create_dataset(name, shape, [dtype=<Numpy dtype>], **kwds) create_dataset(name, data=<Numpy array>, **kwds)
The default dtype is ‘=f4’ (single-precision float).
Additional keywords (“*” is default):
Open a dataset, or create it if it doesn’t exist.
Checks if a dataset with compatible shape and dtype exists, and creates one if it doesn’t. Raises TypeError if an incompatible dataset (or group) already exists.
By default, datatypes are compared for loss-of-precision only. To require an exact match, set keyword “exact” to True. Shapes are always compared exactly.
Keyword arguments are only used when creating a new dataset; they are ignored if an dataset with matching shape and dtype already exists. See create_dataset for a list of legal keywords.
Copy an object or group (Requires HDF5 1.8).
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
Retrieve item “name”, or “default” if it’s not in this group.
Properties common to all HDF5 objects:
Return the parent group of this object.
This is always equivalent to file[posixpath.basename(obj.name)].