6.11.2 为文本数据包装字节流
元素字节流(如套接字)可以被包装为一个层来处理串编码和解码,从而可以更容易地用于处理文本数据。TextIOWrapper类支持读写。write_through参数会禁用缓冲,并且立即将写至包装器的所有数据刷新输出到底层缓冲区。
import io
# Write to a buffer.
output = io.BytesIO()
wrapper = io.TextIOWrapper(
output,
encoding='utf-8',
write_through=True,
)
wrapper.write('This goes into the buffer. ')
wrapper.write('áçÉ')
# Retrieve the value written.
print(output.getvalue())
output.close() # Discard buffer momory.
# Initialize a read buffer.
input = io.BytesIO(
b'Inital value for read buffer with unicode characters ' +
'áçÉ'.encode('utf-8')
)
wrapper = io.TextIOWrapper(input,encoding='utf-8')
# Read from the buffer.
print(wrapper.read())
这个例子使用了一个BytesIO实例作为流。对应bz2,http.server和subprocess的例子展示了如何对其他类型的类文件的对象使用TextIOWrapper。
运行结果: