Skip to content

Instantly share code, notes, and snippets.

@takluyver
Created October 15, 2020 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takluyver/32512eb5367d11d013029af5fbf1d3e1 to your computer and use it in GitHub Desktop.
Save takluyver/32512eb5367d11d013029af5fbf1d3e1 to your computer and use it in GitHub Desktop.
Read HDF5 strings as str with h5py 2.x and 3.0
"""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