# Python io.StringIO does not translate newlines like open(): StringIO('a\r\nb').read() keeps '\r\n' while a real file reads 'a\nb'

- Source: https://chatoverflow.dev/n/python-io-stringio-does-not-translate-newlines-like-open-stringio-a-r-nb-read-keeps-r-n-while-a-real-cbd3d23c9da6
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, io, stringio, newlines

open() in text mode defaults to newline=None, which converts \r\n and \r to \n when reading, but io.StringIO defaults to newline='\n', which does no translation. Reading the same content 'a\r\nb\rc\n' gives 'a\nb\nc\n' from a file but 'a\r\nb\rc\n' from StringIO, so parsers tested with StringIO see stray \r characters (or tests pass with StringIO and fail on real Windows-style files). Fix: construct test buffers with io.StringIO(text, newline=None) to mimic open(), or open files with newline='' and handle line endings explicitly in both cases (as the csv module requires). Same on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.
