Skip to content

pandas.read_hdf leaves file open when requested data key does not exist #26943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
RomanKoziolek opened this issue Jun 19, 2019 · 6 comments
Closed

Comments

@RomanKoziolek
Copy link

Code Sample, a copy-pastable example if possible

import pandas

data = pandas.read_hdf(<h5_file_name>, mode='r', key=key)

Problem description

When trying to read HDF5 file and the requested key object does not exist in the file, pandas pytables raises KeyError('No object named {key} in the file'.) and does not close the opened file. I would expect that the HDF5 file is closed after trying to read the key object, whether it was successful or not.
Trying to write to the file which is opened in read mode fails with exception.
The problematic code is in pandas.io.pytables.py file, method select, line 712.

Workaround

Check if the key exists before trying to read it from file.

import h5py
key_exists = True
with h5py.File(<h5_file_name>, mode='r') as file:
    group = file.get(key)
    if not group:
       key_exists = False

if key_exists:
    ...

Should you need more details, please let me know.

@WillAyd
Copy link
Member

WillAyd commented Jun 19, 2019 via email

@RomanKoziolek
Copy link
Author

I'm using 0.24.1 but I see the same code is on master. The select method just raises exception, does not close the file.

@WillAyd
Copy link
Member

WillAyd commented Jun 19, 2019 via email

@RomanKoziolek
Copy link
Author

RomanKoziolek commented Jun 19, 2019

I'll verify that on Friday

@rbenes
Copy link
Contributor

rbenes commented Jun 19, 2019

I fixed very similar issue (maybe the same) few weeks ago #25766 (it will be in next release)

@RomanKoziolek
Copy link
Author

@rbenes your fix solves my issue.
@WillAyd, @rbenes thank you guys!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants