Repository: pandas-dev/pandas

Issue:
read_hdf does not close store when raise KeyError
#### Code Sample, a copy-pastable example if possible

```python
import pandas as pd
df = pd.DataFrame({'a': range(10), 'b': range(10)})

df.to_hdf('/tmp/1.hdf', 'k1')
try:
    pd.read_hdf('/tmp/1.hdf', 'k2')
except Exception as e:
    print(type(e))
    print(e)
    
df.to_hdf('/tmp/1.hdf', 'k2')
```
#### Problem description
<type 'exceptions.KeyError'>
'No object named k2 in the file'

The file '/tmp/1.hdf' is already opened, but in read-only mode.  Please close it before reopening in append mode.

#### Expected Output
should not raise Exception when: df.to_hdf('/tmp/1.hdf', 'k2')

#### pandas/io/pytables.py line 408
``` python

 except (ValueError, TypeError):  # should also catch KeyError 
```

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.12.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-141-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: zh_CN.UTF-8
LOCALE: None.None

pandas: 0.24.2
pytest: 3.2.4
pip: 19.0.1
setuptools: 39.1.0
Cython: 0.27.3
numpy: 1.14.5
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 5.5.0
sphinx: 1.6.5
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: None
tables: 3.4.2
numexpr: 2.6.4
feather: None
matplotlib: 2.1.0
openpyxl: 2.4.9
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 1.0.2
lxml.etree: 4.1.1
bs4: 4.6.0
html5lib: 0.9999999
sqlalchemy: 1.1.15
pymysql: None
psycopg2: 2.7.3.2 (dt dec pq3 ext lo64)
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None

</details>



Discussion:
Thanks for the report! PRs are always welcome

Resolving patch:
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
--- 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()


Test patch:
diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py
--- 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: