实现说明
stream、buf 定义在模块顶层,中间不经过函数作用域。
使用要点
- 每一步打印都带着自己的标签:
position after writes:、first frame:、lines in buffer:。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 全部导入都来自标准库:io。 文件用顶层绑定保存自己的状态:stream、buf。
代码示例
import io
# BytesIO wraps an in-memory buffer with the file interface
stream = io.BytesIO()
stream.write(b"frame-0001\n")
stream.write(b"frame-0002\n")
print("position after writes:", stream.tell())
# Reads continue from the current position like a real file
stream.seek(0)
print("first frame:", stream.readline().strip())
# getvalue() sees the whole buffer regardless of position
print("lines in buffer:", stream.getvalue().count(b"\n"))
# readinto() fills a preallocated bytearray without extra copies
stream.seek(0)
buf = bytearray(5)
n = stream.readinto(buf)
print("readinto:", n, bytes(buf))