In-memory text processing
Parse or generate text using file-like operations without creating a temporary file.
Python · Module
Python’s io module provides the core stream interfaces for text, binary, and raw input/output. It also supplies in-memory file-like streams such as StringIO and BytesIO.
The io module defines the stream interfaces used for text, binary, and raw I/O. Text streams work with strings and can apply encoding and newline handling, binary streams work with bytes without those text transformations, and raw streams provide a lower-level unbuffered layer.
import ioimport io
with io.StringIO("alpha\nbeta\n") as stream:
lines = stream.readlines()
print([line.rstrip("\n") for line in lines])Uses an in-memory text stream as a file-like object and reads its lines.
Parse or generate text using file-like operations without creating a temporary file.
Transform, buffer, or test binary data through read and write methods.
Implement or adapt stream-oriented APIs using Python’s standard I/O interfaces.
The module covers three broad stream categories: text, binary, and raw I/O. Text streams consume and produce str, binary streams consume bytes-like values and produce bytes, and raw streams are the unbuffered lower-level layer.
Follow-up: Why should a network protocol usually use binary I/O rather than text I/O? Binary I/O avoids implicit encoding, decoding, and newline translation, allowing the protocol to control its byte representation.
StringIO is an in-memory text stream, while BytesIO is an in-memory binary stream. They provide file-like interfaces without requiring a filesystem object.
Follow-up: When is BytesIO preferable to StringIO? Use BytesIO when the data is inherently binary or when exact byte-level handling is required.
Text I/O handles str values and may perform encoding, decoding, and newline processing at the boundary to a byte-oriented backing store. Binary I/O works directly with bytes and performs none of those text transformations.
Follow-up: What design choice avoids platform-dependent text behavior? Specify the intended encoding when creating a text stream, rather than relying on an implicit default.
open()IOBaseRawIOBaseBufferedIOBaseTextIOBaseFileIOBytesIOStringIO