io

The Python io module provides tools for dealing with various types of input/output (I/O), including reading and writing files, handling binary data, and working with streams. It offers a consistent interface to different types of I/O operations and supports both text and binary data.

Here’s a quick example:

Python
>>> import io

>>> # Create an in-memory text stream
>>> text_stream = io.StringIO("Hello, World!")
>>> text_stream.read()
'Hello, World!'

Key Features

  • Provides base classes for file handling
  • Supports both text and binary data I/O
  • Allows creation of in-memory streams
  • Offers high-level and low-level interfaces

Frequently Used Classes and Functions

Object Type Description
io.StringIO Class Creates in-memory text streams
io.BytesIO Class Creates in-memory binary streams
io.open() Function Opens a file or returns a file object
io.BufferedReader Class Provides a buffered interface for reading binary streams
io.BufferedWriter Class Provides a buffered interface for writing binary streams

Examples

Creating an in-memory text stream:

Python
>>> import io
>>> stream = io.StringIO("Welcome to Real Python!")
>>> stream.read()
'Welcome to Real Python!'

Working with binary data using BytesIO:

Python
>>> binary_stream = io.BytesIO(b"Binary data")
>>> binary_stream.read()
b'Binary data'

Common Use Cases

  • Reading and writing to files with different text encodings
  • Handling binary data streams in memory
  • Implementing custom stream classes
  • Performing I/O operations on network data

Real-World Example

Suppose you need to process text data from a file and remove certain words. You can use the io module to read from a file-like object and manipulate the text in memory before writing it back to a file.

Python
>>> import io

>>> text_data = "This is a simple text file with some words to remove."
>>> words_to_remove = {"simple", "some"}
>>> stream = io.StringIO(text_data)
>>> filtered_text = " ".join(
...     word for word in stream.read().split() if word not in words_to_remove
... )

>>> with open("filtered_text.txt", mode="w", encoding="utf-8") as file:
...     file.write(filtered_text)
...

>>> with open("filtered_text.txt", mode="r", encoding="utf-8") as file:
...     print(file.read())
...
This is a text file with words to remove.

In this example, the io module helped to handle text data in memory, process it to remove specific words, and write the filtered text back to a file efficiently.

Tutorial

Reading and Writing Files in Python (Guide)

In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 10, 2025