Skip to content

io Module Complexity

The io module provides core I/O classes for working with binary and text data, including in-memory streams and file-like objects.

Complexity Reference

Operation Time Space Notes
StringIO() creation O(1) O(1) Create empty string buffer
StringIO.write() O(n) amortized O(n) n = string length; amortized due to buffer resizing
StringIO.read() O(n) O(n) n = bytes to read
StringIO.getvalue() O(n) O(n) n = total buffer size; returns copy
BytesIO() creation O(1) O(1) Create empty bytes buffer
BytesIO.write() O(n) amortized O(n) n = bytes length; amortized due to buffer resizing
BytesIO.read() O(n) O(n) n = bytes to read
BytesIO.getvalue() O(n) O(n) n = total buffer size; returns copy
seek() position change O(1) O(1) Random access pointer
tell() get position O(1) O(1) Return current position

In-Memory Text Streams

StringIO Basics

from io import StringIO

# Create in-memory text stream - O(1)
stream = StringIO()

# Write strings - O(k) amortized for k bytes
stream.write("Hello\n")   # O(5)
stream.write("World\n")   # O(5)

# Get all content - O(n)
content = stream.getvalue()  # O(11) for "Hello\nWorld\n"
print(content)
# Hello
# World

# Reset position to beginning - O(1)
stream.seek(0)

# Read all - O(n)
data = stream.read()
print(data)  # "Hello\nWorld\n"

Writing and Reading

from io import StringIO

stream = StringIO()

# Write data - O(k)
lines = ['apple', 'banana', 'cherry']
for line in lines:
    stream.write(line + '\n')

# Get value - O(n)
output = stream.getvalue()
print(output)
# apple
# banana
# cherry

# Reset and read line by line - O(n)
stream.seek(0)
for line in stream:  # O(n) iteration
    print(f"Line: {line.strip()}")

# Close stream - O(1)
stream.close()

In-Memory Binary Streams

BytesIO Basics

from io import BytesIO

# Create in-memory bytes stream - O(1)
stream = BytesIO()

# Write bytes - O(k) amortized
stream.write(b"Binary ")     # O(7)
stream.write(b"data")        # O(4)

# Get all content - O(n)
content = stream.getvalue()  # b"Binary data"
print(content)

# Reset and read - O(1) seek + O(n) read
stream.seek(0)
data = stream.read()
print(data)  # b"Binary data"

Binary Data Manipulation

from io import BytesIO
import struct

stream = BytesIO()

# Pack binary data - O(k) per write
stream.write(struct.pack('i', 42))      # 4 bytes
stream.write(struct.pack('f', 3.14))    # 4 bytes
stream.write(struct.pack('2s', b'AB'))  # 2 bytes

# Get packed data - O(n)
binary = stream.getvalue()  # 10 bytes total

# Unpack from stream - O(1) seek + O(n) read
stream.seek(0)
value1 = struct.unpack('i', stream.read(4))[0]
value2 = struct.unpack('f', stream.read(4))[0]
value3 = struct.unpack('2s', stream.read(2))[0]

Stream Position Operations

Seeking and Telling

from io import StringIO

stream = StringIO("Hello World")

# Current position - O(1)
print(stream.tell())  # 0

# Seek to position - O(1)