Skip to content

BUG: encoding is ignored for read_csv on FileLike objects - FIX - GH#57954 #57992

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pandas/io/parsers/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
defaultdict,
)
import csv
from io import TextIOBase
import sys
from textwrap import fill
from typing import (
Expand Down Expand Up @@ -655,6 +656,14 @@ def _read(
else:
chunksize = validate_integer("chunksize", chunksize, 1)

encoding = kwds.get("encoding")
if (
encoding
and isinstance(filepath_or_buffer, TextIOBase)
and filepath_or_buffer.encoding != encoding
):
raise ValueError("File's encoding does not match with given encoding")

nrows = kwds.get("nrows", None)

# Check for duplicates in names.
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/io/parser/common/test_read_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from io import StringIO
import os
from pathlib import Path
import uuid

import numpy as np
import pytest
Expand Down Expand Up @@ -322,3 +323,25 @@ def test_on_bad_lines_warn_correct_formatting(all_parsers):
):
result = parser.read_csv(StringIO(data), on_bad_lines="warn")
tm.assert_frame_equal(result, expected)


def test_filetype_encoding_miss_match_with_given_encoding(all_parsers):
# GH#57954

data = """
A,B
Ü,Ä
"""
parser = all_parsers
path = f"__{uuid.uuid4()}__.csv"

with tm.ensure_clean(path) as path:
bytes_data = data.encode("latin1")

with open(path, "wb") as f:
f.write(bytes_data)
msg = "File's encoding does not match with given encoding"
err = ValueError
with pytest.raises(err, match=msg):
with open(path) as f:
parser.read_csv(f, encoding="latin1", on_bad_lines="warn")