Search code examples
pythonh5py

Unable to open a previously opened H5


I have a simple python script that opens an H5 file, edits some of the data and closes it. For some reason it works the first time I run the script but in crashes on the second try.

I was expecting that the error was that I do not close the file but actually I do. As you can see below I edit the fields called backR frontR and I create two new ones Manufacturer and Status then I close.

f = h5py.File(filename, 'r+')
backR = f['back_R']
backR[...] = SelectedBackCoat
frontR = f['front_R']
frontR[...] = SelectedFrontCoat
f.create_dataset('manufacturer', data=SelectedManu)
f.create_dataset('status', data=SelectedState)
f.close()

The second time I run the script for the same file to treat I get the following:

  File "h5py\h5f.pyx", line 85, in h5py.h5f.open

OSError: Unable to open file (file is already open for read-only)

Solution

  • The file is still opened, maybe your script didn't reach f.close()? From this answer to this question, you can try to force close all opened files first. Although you should really debug why your file is still opened.

    pytables (which h5py uses) keeps track of all open files and provides an easy method to force-close all open hdf5 files.

    import tables
    tables.file._open_files.close_all()
    

    If you use the with statement you can enforce closing of file, even if a exception occurs:

    with h5py.File(filename, 'r+') as f:
        f.write(...)