How to close an HDF5 using low level Python API?
<p>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: <a href="http://stackoverflow.com/questions/14653259/how-to-set-cache-settings-while-using-h5py-high-level-interface/14656421?noredirect=1#comment67138276_14656421">How to set cache settings while using h5py high level interface?</a></p>

<p>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 ? </p>

<pre><code>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')
</code></pre>

<p><strong>Additional information:</strong> <br/>
<strong>OS: Windows <br/>
Python: 2.7.7 <br/>
Anaconda Distribution: 2.0.1 <br/>
H5py version: 2.3.0</strong></p>

<p>I think you are looking for .close()</p>

<pre><code>f.close()
</code></pre>

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

<p>I edited the line involving contextlib to be:</p>

<pre><code>with contextlib.closing(h5py.File(filename, fapl=propfaid)) as fid:
</code></pre>

<p>and removed</p>

<pre><code>f = h5py.File(fid)
</code></pre>

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

<pre><code>print fid
&lt;Closed HDF5 file&gt;

os.rename(filename, 'foo2.hdf5')
</code></pre>

<p>No errors and check of directory shows the new name</p>

python anaconda hdf5 h5py