Some text some message..
Back I/O (input/output) streams: module in Python 18 Aug, 2025

io is a standard library module in Python that provides tools for working with different types of I/O (input/output) streams.

When you write:

import io

you get access to a set of classes and functions that let you handle:

  • In-memory file-like objects (like using strings or bytes as if they were files).

  • Text and binary streams (buffered, raw, or text wrappers).

  • Low-level interfaces for custom stream handling.


Common Uses of io

1. In-memory file using string (like a file object for text)

import io

text_stream = io.StringIO("Hello, world!")
print(text_stream.read())   # Output: Hello, world!

Useful when you want to treat a string as if it were a file.


2. In-memory file using bytes

import io

bytes_stream = io.BytesIO(b"Binary data here")
print(bytes_stream.read())   # Output: b'Binary data here'

Helpful when working with binary data in memory (e.g., images, PDFs).


3. Writing to an in-memory stream

import io

buffer = io.StringIO()
buffer.write("First line\n")
buffer.write("Second line")
print(buffer.getvalue())   # Output: First line\nSecond line

4. File handling with io.open (Python 2/3 compatibility)

import io

with io.open("example.txt", "w", encoding="utf-8") as f:
    f.write("Hello file!")

👉 In short:

  • StringIO → text stored in memory.

  • BytesIO → binary data stored in memory.

  • open → extended file handling with encoding support.

  • TextIOWrapper, BufferedReader, BufferedWriter → advanced stream handling.