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.
io
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.
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).
import io
buffer = io.StringIO()
buffer.write("First line\n")
buffer.write("Second line")
print(buffer.getvalue()) # Output: First line\nSecond line
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.