# .h5 file format does not close properly

import h5py #added
hf = h5py.File('../images.h5', 'w') #added
hf.close() #added

h5_file = tables.open_file("images.h5", mode="w")


I also tried:

h5py.File.close(hf)


the error that pops up in both cases is:

ValueError: The file 'restricted_images.h5' is already opened.  Please close it before reopening in write mode.


I've also tried:

if isinstance(obj, h5py.File):   # Just HDF5 files
obj.close()


while

In[]: hf
Out[]: <Closed HDF5 file>


, the file is not closed yet.

• I think the question is best suited for StackOverflow May 26 '19 at 6:58
• as you may have noticed, the outcome is indicating that it's a closed object. May 27 '19 at 2:12

## 1 Answer

You may want to use something like the following snippet:

with h5py.File("some_path.h5") as f:
f["data1"] = some_data

import h5py #added
with h5py.File('../images.h5', 'w') as f:
h5_file = tables.open_file("images.h5", mode="w")
# do what ever you want to do, it will be closed by itself.

• Thank you for your response but it doesn't also work. May 27 '19 at 2:36
• You meant it did not close the file? Consider that outside of the with the file is going to be closed. In your code snippet, it is also denoting that it's been closed already. May 27 '19 at 2:40
• Based on the error, the problem was with opening an already opened file. Actually, I shouldn't create the images.h5 file myself. Thank you so much for your time. This with thing is really useful by the way. May 27 '19 at 7:03