StringIO Buffers Text Streams In Memory

io.StringIO wraps a string as an in-memory text stream, so print(file=...) and csv writers redirect into a buffer instead of touching the filesystem.

PythonData Integrity

Code

pythonsnippet
26 lines
from io import StringIO
import csv

# StringIO 把字符串包成内存里的文本流:凡是收 file 的 API 都能直接用
buffer = StringIO()
print("deploy log", file=buffer)
print("status: ok", file=buffer)
print("cursor after writes:", buffer.tell())

# 读完要先把游标拨回 0,read 才从头开始
buffer.seek(0)
content = buffer.read()
print("read() length:", len(content))
print(content, end="")

# csv 模块写出的行直接落在流里,不落盘
out = StringIO()
writer = csv.writer(out)
writer.writerow(["service", "ms"])
writer.writerow(["billing", 412])
print("csv payload lines:", out.getvalue().splitlines())

# print(file=...) 同样把输出重定向进流
sink = StringIO()
print("captured line", file=sink)
print("captured:", sink.getvalue().strip())

Output

Captured from a sandboxed run of this snippet in the build pipeline.

cursor after writes: 22
read() length: 22
deploy log
status: ok
csv payload lines: ['service,ms', 'billing,412']
captured: captured line

How the snippet works

Top-level bindings buffer, content, out, writer hold the demo state — nothing sits inside a function scope.

Applying it

The run emits 7 labeled sections — deploy log, status: ok, cursor after writes:, read() length:, csv payload lines:, captured line, captured: — one per step.

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `io`, `csv`. Its state lives in module-level bindings: `buffer`, `content`, `out`.