diff options
author | Ralf Gommers <ralf.gommers@googlemail.com> | 2011-04-03 12:04:35 +0200 |
---|---|---|
committer | Ralf Gommers <ralf.gommers@googlemail.com> | 2011-04-03 12:04:35 +0200 |
commit | e340e665adba35a5aba7fac09e28ac1f2e4d949b (patch) | |
tree | 2ac233607fc744e4f4133a84df5501346d58393e | |
parent | a15b605771903c85a103dc0fcad423e9a9eb3a98 (diff) | |
download | numpy-e340e665adba35a5aba7fac09e28ac1f2e4d949b.tar.gz |
ENH: return empty array from loadtxt for an empty file. Closes #1752.
Thanks to Paul Anton Letnes and Derek Homeier.
-rw-r--r-- | numpy/lib/npyio.py | 5 | ||||
-rw-r--r-- | numpy/lib/tests/test_io.py | 9 |
2 files changed, 11 insertions, 3 deletions
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index 263aa82c2..25737cbbe 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -750,7 +750,10 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, while not first_vals: first_line = fh.readline() if not first_line: # EOF reached - raise IOError('End-of-file reached before encountering data.') + # Break out of the loop here, so that we return an empty array. + first_line = '' + first_vals = [] + break first_vals = split_line(first_line) N = len(usecols or first_vals) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 5eb1394e4..9afc5dd0b 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -393,7 +393,12 @@ class TestLoadTxt(TestCase): def test_empty_file(self): c = StringIO() - assert_raises(IOError, np.loadtxt, c) + x = np.loadtxt(c) + assert_equal(x.shape, (0,)) + x = np.loadtxt(c, dtype=np.int64) + assert_equal(x.shape, (0,)) + assert_(x.dtype == np.int64) + def test_unused_converter(self): c = StringIO() @@ -584,7 +589,7 @@ class TestFromTxt(TestCase): import warnings basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' warnings.filterwarnings("ignore") - # Footer too small to get rid of all invalid values + # Footer too small to get rid of all invalid values assert_raises(ValueError, np.genfromtxt, StringIO(basestr), skip_footer=1) # except ValueError: |