On this page
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
- Remember
.seek(0)before reading from a buffer you just wrote to: Writing leaves the cursor at EOF, so.read()returns""/b""unless you rewind (or call.getvalue()). getvalue()returns the full buffer regardless of cursor position, while.read()reads from the current position onward.- Closing a
TextIOWrappercloses its underlying binary buffer too: Callwrapper.detach()first if you still need the underlyingBytesIOor socket stream open.
Common Functions
- io.open() —
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)— Open file and return a stream. Raise OSError upon failure. - io.open_code() —
open_code(path)— Opens the provided file with the intent to import the contents. - io.text_encoding() —
text_encoding(encoding, stacklevel=2, /)— A helper function to choose the text encoding.
Classes & Objects
- io.BlockingIOError — I/O operation would block. (Methods:
.add_note(),.with_traceback()) - io.BufferedIOBase — Base class for buffered IO objects. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.read()) - io.BufferedRandom — A buffered interface to random access streams. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.peek()) - io.BufferedReader — Create a new buffered reader using the given readable raw IO object. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.peek()) - io.BufferedRWPair — A buffered reader and writer object together. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.peek()) - io.BufferedWriter — A buffer for a writeable sequential RawIO object. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.read()) - io.BytesIO — Buffered I/O implementation using an in-memory bytes buffer. (Methods:
.close(),.detach(),.fileno(),.flush(),.getbuffer(),.getvalue()) - io.FileIO — Open a file. (Methods:
.close(),.fileno(),.flush(),.isatty(),.read(),.readable()) - io.IncrementalNewlineDecoder — Codec used when reading a file in universal newlines mode. (Methods:
.decode(),.getstate(),.reset(),.setstate()) - io.IOBase — The abstract base class for all I/O classes. (Methods:
.close(),.fileno(),.flush(),.isatty(),.readable(),.readline()) - io.RawIOBase — Base class for raw binary I/O. (Methods:
.close(),.fileno(),.flush(),.isatty(),.read(),.readable()) - io.Reader — Protocol for simple I/O reader instances. (Methods:
.read()) - io.StringIO — Text I/O implementation using an in-memory buffer. (Methods:
.close(),.detach(),.fileno(),.flush(),.getvalue(),.isatty()) - io.TextIOBase — Base class for text I/O. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.read()) - io.TextIOWrapper — Character and line based layer over a BufferedIOBase object, buffer. (Methods:
.close(),.detach(),.fileno(),.flush(),.isatty(),.read()) - io.UnsupportedOperation —
io.UnsupportedOperationclass. (Methods:.add_note(),.with_traceback()) - io.Writer — Protocol for simple I/O writer instances. (Methods:
.write())
Constants & Attributes
io.DEFAULT_BUFFER_SIZE(int) =131072io.SEEK_CUR(int) =1io.SEEK_END(int) =2io.SEEK_SET(int) =0
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/argparse
- tuts/python3/stdlib_module/asyncio
- tuts/python3/stdlib_module/concurrent
- tuts/python3/stdlib_module/contextvars
- tuts/python3/stdlib_module/ctypes
- tuts/python3/stdlib_module/curses
- tuts/python3/stdlib_module/errno
- tuts/python3/stdlib_module/fcntl
- tuts/python3/stdlib_module/filecmp
- tuts/python3/stdlib_module/fileinput
- tuts/python3/stdlib_module/fnmatch
- tuts/python3/stdlib_module/genericpath
- tuts/python3/stdlib_module/getopt
- tuts/python3/stdlib_module/getpass
- tuts/python3/stdlib_module/glob
- tuts/python3/stdlib_module/grp
- tuts/python3/stdlib_module/inspect
- tuts/python3/stdlib_module/io/BlockingIOError
- tuts/python3/stdlib_module/io/BufferedIOBase
- tuts/python3/stdlib_module/io/BufferedRandom
- tuts/python3/stdlib_module/io/BufferedReader
- tuts/python3/stdlib_module/io/BufferedRWPair
- tuts/python3/stdlib_module/io/BufferedWriter
- tuts/python3/stdlib_module/io/BytesIO
- tuts/python3/stdlib_module/io/FileIO
- tuts/python3/stdlib_module/io/IncrementalNewlineDecoder
- tuts/python3/stdlib_module/io/IOBase
- tuts/python3/stdlib_module/io/open
- tuts/python3/stdlib_module/io/open_code
- tuts/python3/stdlib_module/io/RawIOBase
- tuts/python3/stdlib_module/io/Reader
- tuts/python3/stdlib_module/io/StringIO
- tuts/python3/stdlib_module/io/text_encoding
- tuts/python3/stdlib_module/io/TextIOBase
- tuts/python3/stdlib_module/io/TextIOWrapper
- tuts/python3/stdlib_module/io/UnsupportedOperation
- tuts/python3/stdlib_module/io/Writer
- tuts/python3/stdlib_module/ipaddress
- tuts/python3/stdlib_module/linecache
- tuts/python3/stdlib_module/logging
- tuts/python3/stdlib_module/mmap
- tuts/python3/stdlib_module/msvcrt
- tuts/python3/stdlib_module/multiprocessing
- tuts/python3/stdlib_module/nt
- tuts/python3/stdlib_module/ntpath
- tuts/python3/stdlib_module/optparse
- tuts/python3/stdlib_module/os
- tuts/python3/stdlib_module/pathlib
- tuts/python3/stdlib_module/platform
- tuts/python3/stdlib_module/posix
- tuts/python3/stdlib_module/posixpath
- tuts/python3/stdlib_module/pty
- tuts/python3/stdlib_module/pwd
- tuts/python3/stdlib_module/queue
- tuts/python3/stdlib_module/resource
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/select
- tuts/python3/stdlib_module/selectors
- tuts/python3/stdlib_module/shutil
- tuts/python3/stdlib_module/signal
- tuts/python3/stdlib_module/socket
- tuts/python3/stdlib_module/ssl
- tuts/python3/stdlib_module/stat
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/subprocess
- tuts/python3/stdlib_module/syslog
- tuts/python3/stdlib_module/tempfile
- tuts/python3/stdlib_module/termios
- tuts/python3/stdlib_module/threading
- tuts/python3/stdlib_module/time
- tuts/python3/stdlib_module/tty
- tuts/python3/stdlib_module/winreg
- tuts/python3/stdlib_module/winsound
Related notes
- tuts/python3/stdlib_module/fileinput Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/inspect Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BlockingIOError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BufferedIOBase Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BufferedRandom Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BufferedReader Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BufferedRWPair Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BufferedWriter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/BytesIO Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/io/FileIO Linked here; links to this page; shared tags: #stdlib