summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndré Elimelek de Weber <38350057+andrekwr@users.noreply.github.com>2021-12-03 21:11:36 -0300
committerGitHub <noreply@github.com>2021-12-03 19:11:36 -0500
commita81535a364ca2d5aa277977e53c4e2302cae8ea2 (patch)
treee6986b031451cbdac73bb563e2237e8a77baa0c9
parent8bf4e154e77622c4905edfd2af3f5dd7b79a4957 (diff)
downloadnumpy-a81535a364ca2d5aa277977e53c4e2302cae8ea2.tar.gz
BUG: Fix types of errors raised by genfromtxt (#20389)
-rw-r--r--numpy/lib/npyio.py21
-rw-r--r--numpy/lib/tests/test_io.py4
2 files changed, 14 insertions, 11 deletions
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
index 85e26f094..a839b892a 100644
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -1807,22 +1807,21 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
byte_converters = False
# Initialize the filehandle, the LineSplitter and the NameValidator
+ if isinstance(fname, os_PathLike):
+ fname = os_fspath(fname)
+ if isinstance(fname, str):
+ fid = np.lib._datasource.open(fname, 'rt', encoding=encoding)
+ fid_ctx = contextlib.closing(fid)
+ else:
+ fid = fname
+ fid_ctx = contextlib.nullcontext(fid)
try:
- if isinstance(fname, os_PathLike):
- fname = os_fspath(fname)
- if isinstance(fname, str):
- fid = np.lib._datasource.open(fname, 'rt', encoding=encoding)
- fid_ctx = contextlib.closing(fid)
- else:
- fid = fname
- fid_ctx = contextlib.nullcontext(fid)
fhd = iter(fid)
except TypeError as e:
raise TypeError(
- f"fname must be a string, filehandle, list of strings,\n"
- f"or generator. Got {type(fname)} instead."
+ "fname must be a string, a filehandle, a sequence of strings,\n"
+ f"or an iterator of strings. Got {type(fname)} instead."
) from e
-
with fid_ctx:
split_line = LineSplitter(delimiter=delimiter, comments=comments,
autostrip=autostrip, encoding=encoding)
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index 5201b8e6e..c19660cf0 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -1425,6 +1425,10 @@ class TestFromTxt(LoadTxtBase):
('F', 25.0, 60.0)], dtype=descriptor)
assert_equal(test, control)
+ def test_bad_fname(self):
+ with pytest.raises(TypeError, match='fname must be a string,'):
+ np.genfromtxt(123)
+
def test_commented_header(self):
# Check that names can be retrieved even if the line is commented out.
data = TextIO("""