Skip to content

line terminator issue (again) on windows when writing to_csv() #25048

Closed
@briochh

Description

@briochh

Another addition to windows line-end saga:
Changes in Pandas 0.24.0, related to #20353, seem to cause some strange behaviour in this not so uncommom edge case:

Problem description

When using df.to_csv() to write to an exisitng file handle without explicitly setting newline='' (or newline='\n') in the open statement an extra '\r' is added to the default (on windows) '\r\n' line-end:

data = pd.DataFrame({"string_with_lf": ["a\nbc"], "string_with_crlf": ["a\r\nbc"]})
with open("test2.csv", mode='w') as f:
    data.to_csv(f, index=False)
with open("test2.csv", mode='rb') as f:
    print(f.read())
Expected output

b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'

Current output

b'string_with_lf,string_with_crlf\r\r\n"a\r\nbc","a\r\r\nbc"\r\r\n'

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.7.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 79 Stepping 1, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None
pandas: 0.24.0
pytest: 4.0.2
pip: 18.1
setuptools: 40.6.3
Cython: 0.29.2
numpy: 1.15.4
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 7.2.0
sphinx: 1.8.2
patsy: 0.5.1
dateutil: 2.7.5
pytz: 2018.7
blosc: None
bottleneck: 1.2.1
tables: 3.4.4
numexpr: 2.6.8
feather: None
matplotlib: 3.0.2
openpyxl: 2.5.12
xlrd: 1.2.0
xlwt: 1.3.0
xlsxwriter: 1.1.2
lxml.etree: 4.2.5
bs4: 4.6.3
html5lib: 1.0.1
sqlalchemy: 1.2.15
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    IO CSVread_csv, to_csvWindowsWindows OS

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions