Search code examples
pythonhdf5h5pylow-level

Low-level h5py h5f error: expected bytes, found str


I am trying to create an hdf5 file-handler with modified cache settings, as follows:

import h5py
import contextlib

def hdf5_handler(filename, mode="r"):
    h5py.File(filename, "a").close()
    propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)
    settings = list(propfaid.get_cache())
    settings[1] = 0
    settings[2] = 0
    propfaid.set_cache(*settings)
    with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid:
        return h5py.File(fid, mode)

#############
hdf5 = hdf5_handler("/tmp/foo.hdf5", "a")

But it gives the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-121-35fa9f73a406> in <module>()
     99         return h5py.File(fid, mode)
    100 #############
--> 101 hdf5 = hdf5_handler("/tmp/foo.hdf5", "a")

<ipython-input-121-35fa9f73a406> in hdf5_handler(filename, mode)
     96     settings[2] = 0
     97     propfaid.set_cache(*settings)
---> 98     with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid:
     99         return h5py.File(fid, mode)
    100 #############

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/h5f.pyx in h5py.h5f.open()

TypeError: expected bytes, str found

Python version: 3.5.5 h5py version: '2.8.0'

I also found similar code at the following but that also does not work for me with the same error: How to set cache settings while using h5py high level interface?


Solution

  • Convert your string to bytes before:

    hdf5 = hdf5_handler(bytes("/tmp/foo.hdf5",encoding="utf-8"), "a")