Python StringIO:在内存中读写文本流
通过字符位置、整行读取、截断和真实单元测试,掌握 io.StringIO 的读写行为。
学完这一章,你能够
- 通过字符位置、整行读取、截断和真实单元测试,掌握 io.StringIO 的读写行为。
创建文本流并核对字符位置
Python 3 用 from io import StringIO 导入这个类。它提供与文本文件相似的读写接口,内容保存在内存。适合临时拼接文本和为接收文件对象的函数提供测试替身。大输入会消耗内存,性能取决于数据量和操作方式。
StringIO() 创建空流,StringIO(初始文本) 创建带数据的流。两种情况下游标都在开头。write 写入 str,返回输入字符数并推进位置。写入已有内容处会覆盖,追加前可先 seek(0, 2)。二进制数据可用 io.BytesIO。
在 CPython 3.12 的 StringIO 中,绝对位置按文本字符计数。一个补充平面的 Unicode 字符也只占一个位置。磁盘文本流的 tell 通常返回用于恢复的值,二进制流则按字节移动。三种位置含义应分别观察。
在 Windows 的 CPython 3.12.14 上,以相同的 262144 行文本分别写入 StringIO 和 UTF-8 临时文件,再分块读回核对,两者输出字节一致。这组测试里,内存流用时较短,Python 内存分配峰值约 34 MiB,临时文件约 195 KiB。耗时包含分配追踪开销,临时文件可能使用操作系统缓存,分配峰值也只反映 Python 可追踪的部分。解压本章 ZIP 后运行 python stringio-lab/memory_profile.py,可以在自己的环境复测。
区分当前位置、整行和完整内容
read(size) 从当前位置最多读取 size 个字符,省略或传负数读取余下文本,传 0 得到空串且不移动。写完后游标通常在尾部,先 seek(0) 再读。getvalue 返回完整文本,不改变当前游标,即使已读过前缀也能取得它。
readline(size) 从当前位置读到行尾或字符上限,读取到的换行符包含在结果中。空行可返回换行符,读到 EOF 才在普通读取中得到空串。最后一行也可以没有换行符。
readlines(hint) 从当前位置收集完整行。正数 hint 是累计字符数的提示,返回的行可能使累计长度超过它。以两行各 3 个字符的文本为例,CPython 3.12.14 的 io.StringIO 在 hint=3 时读取两行。同版本的内部纯 Python 实现 _pyio.StringIO 在相等时只读一行,此时 tell() 可能抛出 OSError。传 None、0 或负数均读取剩余各行。需要逐行控制边界时,可以用 readline() 自行累计。
定位、截断和关闭
seek(位置, 0) 可做非负绝对定位,seek(0, 1) 保持当前位置,seek(0, 2) 移到末尾。当前与末尾的非零相对位移不受支持。先用 tell 保存当前位置,再用 seek 恢复。
truncate() 默认截到当前游标。显式给更小长度会缩短内容,游标保持原位。实测 CPython 3.12 中给更大的值只返回所请求长度,不会补长文本。若先把游标移到尾部之外再写入,实测间隔填入空字符。
用 with 管理生命周期,或在完成后调用 close。closed 仍可读取,重复 close 返回 None,关闭后 read 和 getvalue 会报 ValueError。若需要保存结果,在退出 with 之前取得它。
newline 控制换行处理。实测 newline=None 将混合换行规范成 LF,空字符串保留原样。指定 CRLF 时写入的 LF 会转换成 CRLF,若输入已含 CRLF,原 CR 仍保留。write 返回输入长度,存储文本长度可因转换改变。
用内存流测试函数和捕获输出
让函数接收文本输入流和输出流,测试时把它们替换为 StringIO。本站实际运行 unittest,用两条文本验证大小写转换,并用另一个内存流捕获测试报告。这样可以分别检查函数输出与运行器结果。
contextlib.redirect_stdout 可把 print 的文本送到内存流,退出上下文恢复原对象。它修改当前进程的全局标准输出,宜用于受控范围。解压 ZIP 后运行 python python-stringio.py 可重做全部观察。
所需环境:CPython 3.12 标准库
ZIP SHA256:52f60ecddb8d935fd74e668c26623624ade57809be5d57951c439e4c54a4b855
构造、读写与位置接口
| 成员 | 作用和条件 |
|---|---|
| StringIO(initial_value="", newline="\n") | 创建内存文本流,可给初始 str,初始游标为 0。 |
| write(s) | 写入 str,返回输入字符数并推进游标,支持覆盖。 |
| read(size=-1) | 最多读取指定字符数,缺省或负数读取余下。 |
| readline(size=-1) | 读一行或达到字符上限。空行和 EOF 分开处理。 |
| readlines(hint=-1) | 按完整行收集。正 hint 是累计字符数提示,相等时的行为取决于实现。None、0 或负数读取剩余各行。 |
| getvalue() | 返回完整文本,保留当前位置。 |
| seek(offset, whence=0) | 做非负绝对定位,或零偏移的当前位置与末尾定位。 |
| tell() | 返回 StringIO 当前字符位置。磁盘文本流应按其恢复位置的规则使用。 |
| truncate(size=None) | 默认截到当前位置,也可明确缩短到给定长度,游标不动。 |
| close() | 关闭流。结束后常见读写操作报错,重复关闭可行。 |
| closed | 只读布尔状态,with 退出后为 True。 |
本章自编源码与运行范围
"""Observe a text stream in memory and run a real stream-based unit test."""
import io
import json
import sys
import unittest
from contextlib import redirect_stdout
def transform(source, destination):
"""Read a text stream and write its upper-case form to another."""
destination.write(source.read().upper())
class TransformTest(unittest.TestCase):
def test_transform_with_memory_streams(self):
with io.StringIO("pier 7\n北港") as source, io.StringIO() as destination:
transform(source, destination)
self.assertEqual(destination.getvalue(), "PIER 7\n北港")
def observe():
checks = []
def check(name, actual, expected, inputs, operation):
if actual != expected:
raise AssertionError((name, actual, expected))
checks.append(dict(name=name, input=inputs, operation=operation, actual=actual,
expected=expected, passed=True))
def rejects(name, error_type, inputs, operation, call):
try:
call()
except error_type as exc:
check(name, type(exc).__name__, error_type.__name__, inputs, operation)
else:
raise AssertionError(name)
with io.StringIO() as stream:
check("empty StringIO opens at position zero",
[stream.getvalue(), stream.tell(), stream.closed], ["", 0, False], "no initial value",
"Create an open memory stream and inspect its initial state")
counts = [stream.write("北港\n"), stream.write("🚢二号")]
check("writes count Unicode characters and advance",
[counts, stream.tell(), stream.getvalue()], [[3, 3], 6, "北港\n🚢二号"],
["北港\n", "🚢二号"], "Write two chunks and check count, content, and current position")
rejects("text stream rejects bytes", TypeError, "UTF-8 bytes", "Try writing bytes to a text stream",
lambda: stream.write(b"pier"))
check("read from end returns empty", stream.read(), "", "at end of stream", "Read without moving the position")
check("seek to start before full read", [stream.seek(0), stream.read()], [0, "北港\n🚢二号"],
"two previously written chunks", "Rewind and read all remaining text")
stream.seek(0)
read = stream.read(2)
before = stream.tell()
content = stream.getvalue()
check("getvalue does not advance and includes already read text",
[read, before, content, stream.tell(), stream.read(-1)], ["北港", 2, "北港\n🚢二号", 2, "\n🚢二号"],
"cursor after two characters", "Read a prefix, retrieve full contents, and read the remaining text")
check("context exit marks stream closed", stream.closed, True, "previous with block", "Inspect the closed attribute")
check("close is idempotent", stream.close(), None, "already closed stream", "Close the stream again")
rejects("closed stream read fails", ValueError, "closed stream", "Attempt to read", stream.read)
rejects("closed stream getvalue fails", ValueError, "closed stream", "Attempt to retrieve content", stream.getvalue)
with io.StringIO("舰🚢位") as stream:
check("initial value starts at beginning", [stream.tell(), stream.read(2)], [0, "舰🚢"],
"Unicode plus one supplementary code point", "Read the first two characters")
pos = stream.tell()
check("read zero does not move cursor", [stream.read(0), stream.tell()], ["", pos],
"non-EOF position", "Request zero characters and check the saved cursor")
check("initial overwrite and explicit append", [stream.seek(0), stream.write("港"), stream.seek(0, 2),
stream.write("站"), stream.getvalue()], [0, 1, 3, 1, "港🚢位站"], "initialized stream",
"Overwrite at start, then move to end and append one character")
check("seek zero relative to current keeps position", stream.seek(0, 1), 4,
"at end of current text", "Seek a zero displacement from current position")
rejects("nonzero current seek unsupported", OSError, "seek(1, 1)", "Try a nonzero relative current seek",
lambda: stream.seek(1, 1))
rejects("nonzero end seek unsupported", OSError, "seek(-1, 2)", "Try a nonzero relative end seek",
lambda: stream.seek(-1, 2))
rejects("negative absolute seek rejected", ValueError, "seek(-1)", "Try seeking before position zero",
lambda: stream.seek(-1))
check("absolute seek uses StringIO character index", [stream.seek(1), stream.read(1), stream.tell()],
[1, "🚢", 2], "known supplementary character at index 1", "Seek to and read a single Unicode character")
with io.StringIO("蓝湾\n\n尾") as stream:
actual = [stream.readline(1), stream.readline(), stream.readline(), stream.readline(), stream.readline()]
check("readline distinguishes size blank line and EOF", actual, ["蓝", "湾\n", "\n", "尾", ""],
"one ordinary line, one blank line, and unterminated final line", "Read with a bound and then through EOF")
with io.StringIO("甲乙\n丙丁\n戊\n") as stream:
actual = [stream.readlines(3), stream.readlines(), stream.tell()]
check("readlines hint stops after complete lines exceed threshold",
actual, [["甲乙\n", "丙丁\n"], ["戊\n"], 8], "hint=3",
"Read whole lines until cumulative characters exceed hint, then read the remainder")
with io.StringIO("a\nb") as stream:
check("readlines nonpositive hint does not limit",
[stream.readlines(0), stream.seek(0), stream.readlines(-1)], [["a\n", "b"], 0, ["a\n", "b"]],
"same input with zero and negative hints", "Compare remaining full-line lists")
with io.StringIO("甲乙丙丁") as stream:
stream.seek(2)
check("truncate defaults to cursor without moving",
[stream.truncate(), stream.getvalue(), stream.tell()], [2, "甲乙", 2],
"cursor at index 2", "Truncate without a size and inspect text and cursor")
check("explicit truncate leaves cursor beyond shortened text",
[stream.truncate(1), stream.getvalue(), stream.tell()], [1, "甲", 2],
"requested size 1 at cursor 2", "Shorten content explicitly and inspect retained position")
check("large truncate size does not grow CPython StringIO",
[stream.truncate(4), stream.getvalue(), stream.tell()], [4, "甲", 2],
"requested size 4 for length 1", "Compare reported size to actual text in this runtime")
check("write beyond end fills an observed gap",
[stream.seek(3), stream.read(), stream.write("乙"), stream.getvalue()],
[3, "", 1, "甲\0\0乙"], "seek to index 3 beyond length 1",
"Read from beyond end, then write at that position")
for newline, expected in ((None, "甲\n乙\n丙\n"), ("", "甲\r\n乙\r丙\n"), ("\r\n", "甲\r\r\n乙\r丙\r\n")):
with io.StringIO(newline=newline) as stream:
count = stream.write("甲\r\n乙\r丙\n")
check("newline policy " + repr(newline), [count, stream.getvalue()], [7, expected],
{"newline": newline, "input": "甲\r\n乙\r丙\n"}, "Write mixed line endings and compare stored text")
with io.StringIO() as target:
suite = unittest.TestSuite([TransformTest("test_transform_with_memory_streams")])
result = unittest.TextTestRunner(stream=target, verbosity=2).run(suite)
check("real unittest tests both memory streams",
[result.testsRun, result.wasSuccessful(), "test_transform_with_memory_streams" in target.getvalue()],
[1, True, True], "test fixture and independent runner output",
"Run a unittest and confirm its asserted transformation and captured report")
original = sys.stdout
with io.StringIO() as target:
with redirect_stdout(target):
print("港口就绪")
check("redirected print and original stdout restored",
[target.getvalue(), sys.stdout is original], ["港口就绪\n", True],
"redirect_stdout with a memory stream", "Capture text and verify stdout restored by identity")
with io.BytesIO(b"\xe5\x8c\x97") as binary:
check("BytesIO works in bytes instead of text", [binary.read(1).hex(), binary.tell()],
["e5", 1], "UTF-8 bytes for 北", "Read one byte and inspect the byte position")
return checks
if __name__ == "__main__":
print(json.dumps(observe(), ensure_ascii=True, indent=2))
所需环境:CPython text-memory stream positions, line hints, lifecycle and real unittest
当前源码 SHA256:8cc47f979a25f5dbe62f35914bb7dd898b981caea418c4d8f68b62dce47e5574
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。