Table of Contents

import io

import io is a Python import that provides in-memory file-like objects. Use StringIO to treat strings as files, and BytesIO for binary data.

Example

# Python
# description: read/write to in-memory file objects
 
import io
 
# String buffer
string_buffer = io.StringIO()
string_buffer.write("Hello, ")
string_buffer.write("World!")
 
# Get contents
contents = string_buffer.getvalue()
print(contents)  # Hello, World!
 
# Read from string buffer
string_buffer.seek(0)  # Reset to start
print(string_buffer.read())  # Hello, World!
 
# Binary buffer
binary_buffer = io.BytesIO()
binary_buffer.write(b"Binary data")
 
binary_buffer.seek(0)
print(binary_buffer.read())  # b'Binary data'
 
# Use as file-like object
text_file = io.StringIO("Line 1\nLine 2\nLine 3\n")
for line in text_file:
    print(line.strip())

Common classes