← 中文资源

简体中文版本

BytesIO 把字节当文件用

BytesIO 把内存中的字节缓冲区包装成文件接口:write、seek、readline、getvalue 与 readinto 全部可用,测试二进制解析时全程不碰磁盘。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

position after writes: 20
first frame: b'frame-0001frame-0002'
lines in buffer: 21
readinto: 5 b'frame'

实现说明

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))