Skip to content

BUG: pd.read_hdf leaves files open if it raises an IndexError exception #52781

Closed
@graingert

Description

@graingert

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import sys
import pathlib
import tempfile
import pandas as pd
import contextlib

@contextlib.contextmanager
def _tmp_path():
    with tempfile.TemporaryDirectory() as path_str:
        yield pathlib.Path(path_str)


def main():
    with _tmp_path() as tmp_path:
        df = pd.DataFrame({"A": [], "B": []}, index=[])
        df.to_hdf(tmp_path / "data.h5", format="fixed", key="df", mode="w")
        try:
            pd.read_hdf(tmp_path / "data.h5", "/df", mode="r", stop=0)
        except IndexError:
            pass

if __name__ == "__main__":
    sys.exit(main())

Issue Description

this prints Closing remaining open files:/tmp/tmp3yi3ev9z/data.h5...done

Expected Behavior

should print nothing

Installed Versions

INSTALLED VERSIONS

commit : 478d340
python : 3.11.3.final.0
python-bits : 64
OS : Linux
OS-release : 5.19.0-38-generic
Version : #39~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 17 21:16:15 UTC 2
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8

pandas : 2.0.0
numpy : 1.24.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.6.1
pip : 23.1
Cython : None
pytest : 7.3.1
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.12.0
pandas_datareader: None
bs4 : None
bottleneck : None
brotli :
fastparquet : 2023.2.0
fsspec : 2023.4.0
gcsfs : None
matplotlib : None
numba : None
numexpr : 2.8.4
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 11.0.0
pyreadstat : None
pyxlsb : None
s3fs : 2023.4.0
scipy : 1.10.1
snappy :
sqlalchemy : 1.4.46
tables : 3.8.0
tabulate : None
xarray : 2023.4.1
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions