On this page
  1. io
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Wrapping a Binary Stream as UTF-8 Text (TextIOWrapper)
  7. 2. Accepting Any File-Like Object in Function Signatures
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

io

Prev: inspect | Up: stdlib_module | Next: ipaddress
Rel: pathlib, os, time, fileinput, stat
Ref: docs.python.org — io
Tags: #public #python3 #stdlib


Import

import io

Overview

Core stream abstractions (IOBase, RawIOBase, BufferedIOBase, TextIOBase) powering Python's open() plus in-memory file-like buffers (StringIO for text, BytesIO for binary). Reach for io.StringIO and io.BytesIO in unit tests, CSV/JSON/archive assembly, and APIs expecting a file-like object without touching disk.

Quick Start

import io

text_buf = io.StringIO()
text_buf.write("line 1\nline 2\n")
text_buf.seek(0)
assert text_buf.readline() == "line 1\n"

bin_buf = io.BytesIO(b"\x89PNG")
assert bin_buf.read(4) == b"\x89PNG"

Implementation Walkthrough

1. Wrapping a Binary Stream as UTF-8 Text (TextIOWrapper)

Useful when a library (like zipfile.ZipFile.open() or gzip) hands you a binary stream and you want line-by-line text iteration without reading everything into memory:

import io

raw_bytes = io.BytesIO("café\nnaïve\n".encode("utf-8"))
with io.TextIOWrapper(raw_bytes, encoding="utf-8") as text_stream:
    lines = [line.strip() for line in text_stream]
assert lines == ["café", "naïve"]

2. Accepting Any File-Like Object in Function Signatures

import io
from typing import TextIO

def count_lines(stream: io.TextIOBase | TextIO) -> int:
    return sum(1 for _ in stream)

assert count_lines(io.StringIO("a\nb\nc\n")) == 3

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes