From 51e6adb0e34f344ab8014c56577ad4fa16c828ef Mon Sep 17 00:00:00 2001 From: iamsimha Date: Tue, 2 Aug 2016 00:52:42 +0530 Subject: [PATCH] BUG: disallow 'w' mode in pd.read_hdf (#13623) (#13858) --- doc/source/whatsnew/v0.19.0.txt | 1 + pandas/io/pytables.py | 4 ++++ pandas/io/tests/test_pytables.py | 11 ++++++++++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v0.19.0.txt b/doc/source/whatsnew/v0.19.0.txt index 62091d7ff03ff..1d69579df21df 100644 --- a/doc/source/whatsnew/v0.19.0.txt +++ b/doc/source/whatsnew/v0.19.0.txt @@ -379,6 +379,7 @@ API changes - The ``pd.read_json`` and ``DataFrame.to_json`` has gained support for reading and writing json lines with ``lines`` option see :ref:`Line delimited json ` (:issue:`9180`) - ``pd.Timedelta(None)`` is now accepted and will return ``NaT``, mirroring ``pd.Timestamp`` (:issue:`13687`) - ``Timestamp``, ``Period``, ``DatetimeIndex``, ``PeriodIndex`` and ``.dt`` accessor have gained a ``.is_leap_year`` property to check whether the date belongs to a leap year. (:issue:`13727`) +- ``pd.read_hdf`` will now raise a ``ValueError`` instead of ``KeyError``, if a mode other than ``r``, ``r+`` and ``a`` is supplied. (:issue:`13623`) .. _whatsnew_0190.api.tolist: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 7503b21160250..b2da4218db99b 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -303,6 +303,10 @@ def read_hdf(path_or_buf, key=None, **kwargs): """ + if kwargs.get('mode', 'a') not in ['r', 'r+', 'a']: + raise ValueError('mode {0} is not allowed while performing a read. ' + 'Allowed modes are r, r+ and a.' + .format(kwargs.get('mode'))) # grab the scope if 'where' in kwargs: kwargs['where'] = _ensure_term(kwargs['where'], scope_level=1) diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py index e214ea5237f30..e9ba80c3a026a 100644 --- a/pandas/io/tests/test_pytables.py +++ b/pandas/io/tests/test_pytables.py @@ -531,16 +531,25 @@ def f(): # conv read if mode in ['w']: - self.assertRaises(KeyError, read_hdf, + self.assertRaises(ValueError, read_hdf, path, 'df', mode=mode) else: result = read_hdf(path, 'df', mode=mode) assert_frame_equal(result, df) + def check_default_mode(): + + # read_hdf uses default mode + with ensure_clean_path(self.path) as path: + df.to_hdf(path, 'df', mode='w') + result = read_hdf(path, 'df') + assert_frame_equal(result, df) + check('r') check('r+') check('a') check('w') + check_default_mode() def test_reopen_handle(self):