~ubuntu-branches/debian/experimental/h5py/experimental

« back to all changes in this revision

Viewing changes to examples/groups.py

  • Committer: Bazaar Package Importer
  • Author(s): Soeren Sonnenburg
  • Date: 2009-09-24 11:08:03 UTC
  • mfrom: (2.1.1 sid)
  • Revision ID: james.westby@ubuntu.com-20090924110803-hz0en6f43x8opgj4
Tags: 1.2.1-2
Build-depend on hdf5 >= 1.8.3 and enable api 1.8 (Closes: #548049)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
"""
 
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
 
6
    and groups.
 
7
 
 
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
 
12
    attributes.
 
13
 
 
14
    HDF5 for Python is available at h5py.alfven.org.
 
15
"""
 
16
 
 
17
import numpy as np
 
18
import h5py
 
19
 
 
20
f = h5py.File('myfile.hdf5','w')
 
21
 
 
22
# The file object is also the "root group" ("/") in HDF5.  It's currently
 
23
# empty:
 
24
print "Number of items in the root group: %d" % len(f)
 
25
 
 
26
# Create some groups
 
27
g1 = f.create_group('Group1')
 
28
g2 = f.create_group('Another Group')
 
29
g3 = f.create_group('Yet another group')
 
30
 
 
31
# All groups, including the root group, support a basic dictionary-style
 
32
# interface
 
33
print "There are now %d items in the root group" % len(f)
 
34
print "They are: %s" % ", ".join(f)  # iterating yields member names
 
35
 
 
36
# Groups can contain subgroups themselves
 
37
sub1 = g1.create_group("Subgroup1")
 
38
 
 
39
# Prints "/Group1/Subgroup1"
 
40
print "Full name of subgroup is %s" % sub1.name
 
41
 
 
42
# You can retrieve them using __getitem__ syntax
 
43
sub2 = g1['Subgroup1']
 
44
 
 
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')
 
50
 
 
51
# Create datasets using group methods.  (See other examples for a more in-
 
52
# depth introduction to datasets).
 
53
 
 
54
data = np.arange(100*100).reshape((100,100))
 
55
 
 
56
dset = sub1.create_dataset("My dataset", data=data)
 
57
 
 
58
print "The new dataset has full name %s, shape %s and type %s" % \
 
59
        (dset.name, dset.shape, dset.dtype) 
 
60
 
 
61
# Closing the file closes all open objects
 
62
f.close()
 
63
 
 
64
 
 
65
 
 
66
 
 
67
 
 
68