1
votes

I was able to modify the cache settings of an HDF5 file by combining both the high and low level Python h5py API as defined in the following Stack Overflow question: How to set cache settings while using h5py high level interface?

I am getting an error saying that the h5 file is still open when I try to rename the file. The Python "with" statement with the contextlib does not seem to be closing the file after the HDF5 writing operation is completed and the file is flushed. How can I make sure that the file is closed using either the low-level or high-level API? Could you please provide an example ?

import h5py
import contextlib
import os

filename = 'foo_2.h5'
propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)
settings = list(propfaid.get_cache())
settings[2] *= 5
propfaid.set_cache(*settings)

with h5py.File(filename, 'w') as hf:
    print 'file created'

with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid:

    f = h5py.File(fid)
    f.flush()

    # f.close() Seems to be working only in Python 3.4.3 but not in 2.7.7
    #and the "with contextlib.closing(...)  does not work on either version
    f.close()

os.rename(filename, 'foo_2.h5')

Additional information:
OS: Windows
Python: 2.7.7
Anaconda Distribution: 2.0.1
H5py version: 2.3.0

1
What is the exact error message? - unutbu
WindowsError: [Error 32] The process cannot access the file because it is being used by another process - zd5151
You could get this error if somewhere else in the code the file is being opened (but not closed). Or, if some other process (such as a virus checker or some other application has the file open.) You might try using Unlocker or Process Explorer to see what applications have the file open. I don't see any error in the code you posted. It, in itself, does not raise an error (at least not for me on linux). - unutbu
I have added a working script for testing. Which version of Python are you running in your linux machine ? - zd5151
Thank you. I have opened the issue Unable to close an HDF5 using low level Python API - zd5151

1 Answers

0
votes

I think you are looking for .close()

f.close()

Although looking closer, I'm not sure why contextlib.closing(...) didn't work.

I edited the line involving contextlib to be:

with contextlib.closing(h5py.File(filename, fapl=propfaid)) as fid:

and removed

f = h5py.File(fid)

Afterwards, I could check that fid was closed and renaming file worked as expected.

print fid
<Closed HDF5 file>

os.rename(filename, 'foo2.hdf5')

No errors and check of directory shows the new name