How do you emulate a seekable binary sample file in memory?

BytesIO exposes a byte buffer as a file-like object with a shared read/write cursor.

Python example and interpretation

Reading immediately after writing ABC encounters end-of-file. Seek to offset one to read BC and test how a parser handles cursor position.

import io
f=io.BytesIO()
f.write(b'ABC')
end=f.read()
f.seek(1)
[end.hex(),f.read(2).hex()]

Result ['', '4243']

中文

怎样在内存中模拟可回读的二进制样本文件?

BytesIO 将字节缓冲区作为文件对象暴露,读写共享当前游标。

Python 算例与适用条件

写入 ABC 后直接读会到达文件末尾。回到偏移 1 后读取两个字节才能得到 BC,适合验证解析器的游标处理。

import io
f=io.BytesIO()
f.write(b'ABC')
end=f.read()
f.seek(1)
[end.hex(),f.read(2).hex()]

结果 ['', '4243']

References / 参考来源

Keep reading / 继续阅读