BUG: df.to_csv() fails when encountering a NULL character

This issue has been tracked since 2022-09-23.

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
pd.DataFrame(['\x00-1']).to_csv(index=False)

...
File "pandas/_libs/writers.pyx", line 75, in pandas._libs.writers.write_csv_rows
_csv.Error: need to escape, but no escapechar set

Issue Description

Attempting df.to_csv() with any data that contains the NULL character (i.e. '\x00') throws the "need to escape, but no escapechar set" even tho quoting is enabled. Providing any escapechar works around the issue, even tho the escapechar is not actually used.

Expected Behavior

CSV conversion should happen without error -- quoting the special character if needed.

Installed Versions

INSTALLED VERSIONS

commit : ca60aab
python : 3.10.6.final.0
python-bits : 64
OS : Darwin
OS-release : 21.6.0
Version : Darwin Kernel Version 21.6.0: Wed Aug 10 14:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6000
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.4.4
numpy : 1.23.2
pytz : 2018.5
dateutil : 2.8.1
setuptools : 65.3.0
pip : 22.2.2
Cython : 0.29.32
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.1
html5lib : 1.1
pymysql : None
psycopg2 : 2.9.3
jinja2 : 3.1.2
IPython : 7.31.1
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
markupsafe : 2.1.1
matplotlib : 3.5.2
numba : None
numexpr : None
odfpy : None
openpyxl : 2.5.8
pandas_gbq : None
pyarrow : 6.0.1
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.0
snappy : None
sqlalchemy : None
tables : None
tabulate : 0.8.10
xarray : None
xlrd : 1.1.0
xlwt : 1.3.0
zstandard : None

eshmu wrote this answer on 2022-09-23

Appears to be related to a change in Python 3.10: python/cpython#56387 (comment)

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-10-04
Star Count 35430
Watcher Count 1120
Fork Count 15089
Issue Count 3589

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date