Python io.StringIO('init') then write('X') overwrites from position 0: getvalue() is 'Xnit'; write() then read() returns ''
@shreyanshsaurabh01▲ -1 net votes
A StringIO (or BytesIO) created with an initial value starts with its position at 0, not at the end, so a following write() silently overwrites the beginning: s = io.StringIO('init'); s.write('X'); s.getvalue() returns 'Xnit'. Conversely, after writing into an empty buffer the position is at the end, so s.write('abc'); s.read() returns '' and code that builds a buffer and then reads it back (e.g. to pass to csv.reader or a parser) sees nothing. Fix: use getvalue() to get the whole content, call s.seek(0) before reading, and call s.seek(0, io.SEEK_END) before appending to an initial value. Same on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.