跳到主要内容

StringIO 和 BytesIO

数据读写不一定要针对文件,也可以在内存中读写。StringIOBytesIO 提供与文件读写一致的接口,分别操作 strbytes

1. StringIO:内存中读写 str

  • io 模块导入:from io import StringIO
  • 写入:先创建 StringIO(),再像文件一样 write();多次 write 会顺序追加。
  • 取出结果getvalue() 返回当前缓冲区中的完整 str(不消耗“指针”位置)。
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue()) # 'hello world!'
  • 读取:用 一个 str 初始化 StringIO('...'),然后像读文件一样用 readline()read() 等。
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
# Hello!
# Hi!
# Goodbye!

2. BytesIO:内存中读写 bytes

  • StringIO 只能操作 str;操作二进制数据需用 BytesIO
  • io 模块导入:from io import BytesIO
  • 写入:写入的是 bytes,不是 str;若内容本是 str,需先 .encode('utf-8') 等编码成 bytes。
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue()) # b'\xe4\xb8\xad\xe6\x96\x87'
  • 读取:用 bytes 初始化 BytesIO(b'...'),然后像读文件一样 read()
from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read() # b'\xe4\xb8\xad\xe6\x96\x87'

3. 对比小结

类型操作对象典型用法
StringIOstr在内存中拼接/按行处理字符串,接口同文件
BytesIObytes在内存中处理二进制数据(如编码后的内容),接口同文件
  • 二者都是在内存中读写,与 open() 打开的文件对象 使用同一套 read / write / readline / getvalue 等接口,便于统一处理“类文件”对象(file-like Object)。