Skip to content

Commit deedac0

Browse files
committed
BUG: use TypeError (not OSError) when read_csv expects file path name or file-like object
1 parent 1ab776e commit deedac0

File tree

4 files changed

+15
-2
lines changed

4 files changed

+15
-2
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,7 @@ I/O
385385
- Column headers are dropped when constructing a :class:`DataFrame` from a sqlalchemy's ``Row`` object (:issue:`40682`)
386386
- Bug in unpickling a :class:`Index` with object dtype incorrectly inferring numeric dtypes (:issue:`43188`)
387387
- Bug in :func:`read_csv` where reading multi-header input with unequal lengths incorrectly raising uncontrolled ``IndexError`` (:issue:`43102`)
388+
- Bug in :func:`read_csv`, changed exception class when expecting a file path name or file-like object from ``OSError`` to ``TypeError`` (:issue:`43366`)
388389

389390
Period
390391
^^^^^^

pandas/_libs/parsers.pyx

+2-2
Original file line numberDiff line numberDiff line change
@@ -607,8 +607,8 @@ cdef class TextReader:
607607
void *ptr
608608

609609
if not hasattr(source, "read"):
610-
raise IOError(f'Expected file path name or file-like object, '
611-
f'got {type(source)} type')
610+
raise TypeError('Expected file path name or file-like object, '
611+
f'got {type(source)} type')
612612

613613
ptr = new_rd_source(source)
614614
self.parser.source = ptr

pandas/io/common.py

+4
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,10 @@ def get_handle(
738738
isinstance(ioargs.filepath_or_buffer, str) or ioargs.should_close
739739
)
740740

741+
if not hasattr(handle, "read"):
742+
raise TypeError('Expected file path name or file-like object, '
743+
f'got {type(ioargs.filepath_or_buffer)} type')
744+
741745
handles.reverse() # close the most recently added buffer first
742746
if ioargs.should_close:
743747
assert not isinstance(ioargs.filepath_or_buffer, str)

pandas/tests/io/parser/common/test_common_basic.py

+8
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,14 @@ def test_raise_on_sep_with_delim_whitespace(all_parsers):
493493
parser.read_csv(StringIO(data), sep=r"\s", delim_whitespace=True)
494494

495495

496+
def test_read_filepath_or_buffer(all_parsers):
497+
# see gh-43366
498+
parser = all_parsers
499+
500+
with pytest.raises(TypeError, match="Expected file path name or file-lik"):
501+
parser.read_csv(filepath_or_buffer=b'input')
502+
503+
496504
@xfail_pyarrow
497505
@pytest.mark.parametrize("delim_whitespace", [True, False])
498506
def test_single_char_leading_whitespace(all_parsers, delim_whitespace):

0 commit comments

Comments
 (0)