diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 94f8fd16ea85a..30e38e259cde9 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -353,6 +353,7 @@ I/O - Bug in :meth:`DataFrame.to_string` and :meth:`DataFrame.to_latex` that would lead to incorrect output when the ``header`` keyword is used (:issue:`16718`) - Bug in :func:`read_csv` not properly interpreting the UTF8 encoded filenames on Windows on Python 3.6+ (:issue:`15086`) - Improved performance in :meth:`pandas.read_stata` and :class:`pandas.io.stata.StataReader` when converting columns that have missing values (:issue:`25772`) +- Bug in :func:`read_hdf` not properly closing store after a ``KeyError`` is raised (:issue:`25766`) - Bug in ``read_csv`` which would not raise ``ValueError`` if a column index in ``usecols`` was out of bounds (:issue:`25623`) Plotting diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 42e146ae81839..2dedeaf0a4cda 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -375,7 +375,7 @@ def read_hdf(path_or_buf, key=None, mode='r', **kwargs): 'contains multiple datasets.') key = candidate_only_group._v_pathname return store.select(key, auto_close=auto_close, **kwargs) - except (ValueError, TypeError): + except (ValueError, TypeError, KeyError): # if there is an error, close the store try: store.close() diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 679a24d374115..e45ca1afdcef9 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -1233,6 +1233,19 @@ def test_append_all_nans(self): reloaded = read_hdf(path, 'df_with_missing') tm.assert_frame_equal(df_with_missing, reloaded) + def test_read_missing_key_close_store(self): + # GH 25766 + with ensure_clean_path(self.path) as path: + df = pd.DataFrame({'a': range(2), 'b': range(2)}) + df.to_hdf(path, 'k1') + + with pytest.raises(KeyError): + pd.read_hdf(path, 'k2') + + # smoke test to test that file is properly closed after + # read with KeyError before another write + df.to_hdf(path, 'k2') + def test_append_frame_column_oriented(self): with ensure_clean_store(self.path) as store: