Databases Reference
In-Depth Information
>>>
grp
=
f
.
create_group
(
u'e_with_accent_
\u00E9
'
)
>>>
print
grp
.
name
/e_with_accent_é
On the backend, h5py converts your string to the HDF5-approved UTF-8 encoding
before storing it. When you supply a “regular” or “byte” string (as in most of the previous
examples), h5py uses your string as is. It's technically possible to store non-UTF-8 strings
like this, although such use is strongly discouraged. If you do happen to receive a file
with such “noncompliant” object names, h5py will simply pass back the raw byte string
and let you figure it out.
Using get to Determine Object Types
We mentioned that the familiar dictionary-style method
get
was also available on
Group
objects, and showed how to handle missing group members without raising
KeyError
.
But this version of
get
is a little more capable than the Python
get
.
There are two additional keywords in addition to the dictionary-style
default
:
get
class
and
getlink
. The
getclass
keyword lets you retrieve the
type
of an object without
actually having to open it. At the HDF5 level, this only requires reading some metadata
and is consequently very fast.
Here's an example: first we'll create a file containing a single group and a single dataset:
>>>
f
=
h5py
.
File
(
'get_demo.hdf5'
,
'w'
)
>>>
f
.
create_group
(
'subgroup'
)
>>>
f
.
create_dataset
(
'dataset'
,
(
100
,))
Using
get
, the
type
of object can be retrieved:
>>>
for
name
in
f
:
...
print
name
,
f
.
get
(
name
,
getclass
=
True
)
dataset <class 'h5py._hl.dataset.Dataset'>
subgroup <class 'h5py._hl.group.Group'>
The second keyword,
getlink
, lets you determine the properties of the link involved:
>>>
f
[
'softlink'
]
=
h5py
.
SoftLink
(
'/subgroup'
)
>>>
with
h5py
.
File
(
'get_demo_ext.hdf5'
,
'w'
)
as
f2
:
...
f2
.
create_group
(
'egroup'
)
>>>
f
[
'extlink'
]
=
h5py
.
ExternalLink
(
'get_demo_ext.hdf5'
,
'/egroup'
)
>>>
for
name
in
f
:
...
print
name
,
f
.
get
(
name
,
getlink
=
True
)
dataset <h5py._hl.group.HardLink object at 0x047277F0>
extlink <ExternalLink to "/egroup" in file "get_demo_ext.hdf5"
softlink <SoftLink to "/subgroup">
subgroup <h5py._hl.group.HardLink object at 0x047273B0>