diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 22a2931519ffd..4ff0a7ef0022e 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -348,6 +348,7 @@ I/O ^^^ - :meth:`DataFrame.to_orc` now raising ``ValueError`` when non-default :class:`Index` is given (:issue:`51828`) - :meth:`DataFrame.to_sql` now raising ``ValueError`` when the name param is left empty while using SQLAlchemy to connect (:issue:`52675`) +- Bug in :func:`read_hdf` not properly closing store after a ``IndexError`` is raised (:issue:`52781`) - Bug in :func:`read_html`, style elements were read into DataFrames (:issue:`52197`) - Bug in :func:`read_html`, tail texts were removed together with elements containing ``display:none`` style (:issue:`51629`) - diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 2a522ef6b5171..8de1aaacaf400 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -455,7 +455,7 @@ def read_hdf( chunksize=chunksize, auto_close=auto_close, ) - except (ValueError, TypeError, KeyError): + except (ValueError, TypeError, LookupError): if not isinstance(path_or_buf, HDFStore): # if there is an error, close the store if we opened it. with suppress(AttributeError): diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index 2f2190a352045..61dabf15653f0 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -42,6 +42,20 @@ def test_read_missing_key_close_store(tmp_path, setup_path): df.to_hdf(path, "k2") +def test_read_index_error_close_store(tmp_path, setup_path): + # GH 25766 + path = tmp_path / setup_path + df = DataFrame({"A": [], "B": []}, index=[]) + df.to_hdf(path, "k1") + + with pytest.raises(IndexError, match=r"list index out of range"): + read_hdf(path, "k1", stop=0) + + # smoke test to test that file is properly closed after + # read with IndexError before another write + df.to_hdf(path, "k1") + + def test_read_missing_key_opened_store(tmp_path, setup_path): # GH 28699 path = tmp_path / setup_path