3
HDF5 for Python (h5py) is a Python interface to the HDF5 library. Built
4
on a near-complete Python wrapping of the HDF5 C API, it exposes a simple,
5
NumPy-like interface for interacting with HDF5 files, datasets, attributes
8
This module demonstrates the use of HDF5 groups from h5py. HDF5 groups
9
are analagous to directories in a filesystem; they even use the UNIX-style
10
/path/to/resource syntax. In h5py, groups act like dictionaries. They
11
also provide the necessary methods to create subgroups, datasets, and
14
HDF5 for Python is available at h5py.alfven.org.
20
f = h5py.File('myfile.hdf5','w')
22
# The file object is also the "root group" ("/") in HDF5. It's currently
24
print "Number of items in the root group: %d" % len(f)
27
g1 = f.create_group('Group1')
28
g2 = f.create_group('Another Group')
29
g3 = f.create_group('Yet another group')
31
# All groups, including the root group, support a basic dictionary-style
33
print "There are now %d items in the root group" % len(f)
34
print "They are: %s" % ", ".join(f) # iterating yields member names
36
# Groups can contain subgroups themselves
37
sub1 = g1.create_group("Subgroup1")
39
# Prints "/Group1/Subgroup1"
40
print "Full name of subgroup is %s" % sub1.name
42
# You can retrieve them using __getitem__ syntax
43
sub2 = g1['Subgroup1']
45
# You can attach attributes to groups, just like datasets, containing just
46
# about anything NumPy can handle.
47
g1.attrs['purpose'] = "A demonstration group"
48
g1.attrs['Life, universe, everything'] = 42
49
g1.attrs['A numpy array'] = np.ones((3,), dtype='>i2')
51
# Create datasets using group methods. (See other examples for a more in-
52
# depth introduction to datasets).
54
data = np.arange(100*100).reshape((100,100))
56
dset = sub1.create_dataset("My dataset", data=data)
58
print "The new dataset has full name %s, shape %s and type %s" % \
59
(dset.name, dset.shape, dset.dtype)
61
# Closing the file closes all open objects