BUG: regression in read_csv reading from file stream with encoding

This issue has been created since 2022-09-19.

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
import tempfile

with tempfile.NamedTemporaryFile("wt", encoding="utf-8", delete=False) as f:
    f.write("### DATA\nkey,value\ntables,rectangular\n")

with open(f.name, 'r', encoding="utf-8") as fin:
    fin.readline()
    pd.read_csv(fin)

Issue Description

Fails in TextReader.__cinit__ with EmptyDataError in pandas 1.5.0, while it completed correctly in 1.4.4. Using the system default encoding of "UTF-8" (uppercase) completes correctly as well (as does omitting the encoding argument in open).

File ~/.local/conda/envs/datatoolbox_test/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py:92, in CParserWrapper.__init__(self, src, **kwds)
     89     kwds.pop(key, None)
     91 kwds["dtype"] = ensure_dtype_objs(kwds.get("dtype", None))
---> 92 self._reader = parsers.TextReader(src, **kwds)
     94 self.unnamed_cols = self._reader.unnamed_cols
     96 # error: Cannot determine type of 'names'

File ~/.local/conda/envs/datatoolbox_test/lib/python3.8/site-packages/pandas/_libs/parsers.pyx:554, in pandas._libs.parsers.TextReader.__cinit__()

EmptyDataError: No columns to parse from file

Expected Behavior

No raise. pd.read_csv reads in table.

Installed Versions

INSTALLED VERSIONS

commit : 87cfe4e
python : 3.8.13.final.0
python-bits : 64
OS : Darwin
OS-release : 21.6.0
Version : Darwin Kernel Version 21.6.0: Sat Jun 18 17:07:25 PDT 2022; root:xnu-8020.140.41~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8

pandas : 1.5.0
numpy : 1.23.3
pytz : 2022.2.1
dateutil : 2.8.2
setuptools : 65.3.0
pip : 22.2.2
Cython : None
pytest : 7.1.3
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 3.0.3
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.5.0
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.0
numba : None
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.1
snappy : None
sqlalchemy : None
tables : None
tabulate : 0.8.10
xarray : 2022.6.0
xlrd : 2.0.1
xlwt : 1.3.0
zstandard : None
tzdata : None

twoertwein wrote this answer on 2022-09-19

I can confirm that it works on 1.4.4 (engine="c" and "python") and fails on 1.5.0 for engine="c" but works with engine="python".

I must admit I slightly prefer the failure with the c-engine in 1.5.0. After .readline() the position of the file handle reached the end and should therefore correctly be empty. If you add fin.seek(0) before the read_csv call, it works.
Forget my comment - you intentionally read only one line - not the entire file.

phofl wrote this answer on 2022-09-19

Can confirm

commit 9292530c9eadd70fbff68a3e71c2fc2bea10b3d9
Author: Torsten Wörtwein <[email protected]>
Date:   Mon May 30 16:45:01 2022 -0400

    CLN: Simplify mmap code (#47175)

cc @twoertwein #47175

twoertwein wrote this answer on 2022-09-19

I assume that this shortcut (to make read_csv+mmap faster) is causing an issue:

src = src.buffer # type: ignore[assignment]

In this example

(Pdb) src.tell()
9
(Pdb) src.buffer.tell()
38

TextIOWrapper seems to have read-ahead (since its internal buffer is already at the end).

The following seems to fix this issue src.seek(src.tell()) but I don't know whether that is a good solution.

More Details About Repo
Owner Name pandas-dev
Repo Name pandas
Full Name pandas-dev/pandas
Language Python
Created Date 2010-08-24
Updated Date 2022-09-29
Star Count 35374
Watcher Count 1122
Fork Count 15034
Issue Count 3579

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
:four_leaf_clover: `Proposal`: New plugin `jenkins-github-integ` 0 2022-07-28 2022-08-17
Invalid metadata address 2 2022-02-04 2022-09-18
Filename undo/redo incorrectly sets selection 0 2021-11-18 2022-08-21
Backward search performance is terrible using :-/xxx 2 2021-11-11 2022-08-02
Tag fonts use wrong font 0 2021-10-22 2022-08-02
HI, do you have the dataset download link which can be used in the mainland? 0 2021-10-06 2022-07-29
can you release some training details? 0 2021-05-27 2022-08-01
Google Tag Manager with turbolinks: true duplicates pageView when using Push 6 2019-06-07 2022-09-19
Drag and drop feature 0 2021-07-13 2022-09-23
SpotMarketRequest does not include Parameters 0 2021-05-07 2022-08-28
'file' type in Python2 4 2021-07-11 2022-07-30
The plugin only takes the geolocation once 2 2021-06-14 2022-09-02
Type hint the codebase 0 2022-06-02 2022-09-19
Padding zero or not? 5 2021-12-20 2022-09-29
Cannot update/delete a camera 2 2022-01-08 2022-09-02
publish to standard sbt plugins repo 1 2013-07-30 2022-09-27
Foreign key violation trying to BulkInsert deep owned object graph into SqlServer 2 2022-08-08 2022-09-02
undefined method `amount' for #<Stripe::SetupIntent 3 2021-08-15 2022-08-23
🛑 depviz.moul.io is down 0 2021-07-02 2022-09-20
Radio button set to readonly (invalid HTML5) 1 2021-03-15 2022-09-26
Simple HTTP proxy test using Hoverfly hangs forever 9 2017-09-05 2022-09-13
[Doc] Nginx 的配置方式修改 1 2021-02-01 2022-01-22
JavaScript error is raised if set incorrect defaultValueExpression for matrix dropdown 0 2022-09-04 2022-09-19
建议:spug 保存云的 secretID 和 secretKey 以定期同步云主机信息 0 2022-07-06 2022-09-26
Offline Setup 1 2021-08-17 2022-01-20
Failed deploy: standard_init_linux.go:207: exec user process caused "exec format error" 6 2019-06-09 2021-10-14
Add "URL External" attribute to Button block 0 2021-08-31 2022-09-19
Framebust out of webviews 2 2022-08-13 2022-09-18
Problem generating Video thumbnails, even though ffmpeg is installed 10 2021-04-27 2022-09-26
Add annotation to note at cursor position 0 2022-03-28 2022-07-30
Simultaneous Note/Voice ons don't reap polyphony limit 0 2022-05-31 2022-08-22
Haraka scaling 7 2018-07-24 2022-01-09
New release 2 2021-06-21 2022-01-01
Action Required: Fix Renovate Configuration 0 2021-10-19 2022-09-21
Decimal to binary conversion of numbers 8 2022-02-24 2022-09-27
CLI: Provide a way to remove already indexed files from index 4 2021-07-08 2022-09-11
Turning off printing of values in Interactive mode 1 2020-02-22 2022-09-26
Opening a notebook on remote, closing it, and reopening it does not reuse the same kernel 4 2021-09-21 2022-09-29
simdlib memory leaks 0 2022-01-19 2022-09-08
AprilTag Memory Leak ViSP 3.4.0 4 2022-01-14 2022-08-02
Remove initial-scale=1 from header viewport declaration 1 2021-09-07 2022-09-02
Current state of revision of Configure Screen 4 2022-05-13 2022-09-22
Sending Emails using Firefox Private Relay – (Feature Request) 2 2022-03-29 2022-09-24
Heartbeat views in code are unused 0 2022-03-30 2022-09-26
Ability to see blocked email address, or any information – (Feature Request) 0 2022-03-30 2022-09-26
Allow to reply to CC and BCC – (Feature Request) 0 2022-03-29 2022-09-26
client-go v0.21 leaking go routines when using SPDYExecutor 30 2021-06-24 2022-09-23
Add optional getter type parameter for Store<S> 3 2021-08-06 2022-08-15
Deprecation warning due to invalid escape sequences in Python 3.8 0 2020-02-01 2022-09-08
heightSyle needed for making Text background color height consistent 17 2022-02-25 2022-09-23