Created
October 15, 2020 08:59
-
-
Save takluyver/32512eb5367d11d013029af5fbf1d3e1 to your computer and use it in GitHub Desktop.
Read HDF5 strings as str with h5py 2.x and 3.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Read HDF5 strings to Python str | |
h5py 3.0 changed the APIs for storing and reading strings. | |
This shows how to read strings as Python 3 str if you need | |
to support both old and new h5py. | |
""" | |
import h5py | |
import numpy as np | |
f = h5py.File('foo.h5', 'r') | |
ds = f['data'] | |
if h5py.version.version_tuple[0] == 3: | |
strings = ds.asstr()[()] | |
else: | |
# h5py 2.x | |
if h5py.check_string_dtype(ds.dtype).encoding == 'utf-8': | |
strings = ds[()] | |
else: | |
# HDF5 ASCII strings | |
bytes_data = ds[()] | |
strings = np.array([ | |
b.decode('ascii') for b in bytes_data.flat | |
], dtype=object).reshape(bytes_data.shape) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment