How to close an HDF5 using low level Python API?

2019-08-04 18:16发布

问题:

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:

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