第六章:文件系统-io:文本、十进制和原始流I/O工具-内存中的流

6.11 io:文本、十进制和原始流I/O工具
io模块在解释器的内置open()之上实现了一些类来完成基于文件的输入和输出操作。这些类得到了适当的分解,从而可以针对不同的用途重新组合——例如,支持向一个网络套接字写Unicode数据。

6.11.1 内存中的流
StringIO提供了一种很便利的方式,可以使用文件API(如read(),write()等)处理内存中的文本。有些情况下,与其他一些字符串连接技术相比,使用StringIO构造大字符串可以提供更好的性能。内存中的流缓冲区对测试也很有用,写入磁盘上真正的文件并不会减慢测试套件的速度。

import io

# Write to a buffer.
output = io.StringIO()
output.write('This goes into the buffer. ')
print('And so does this.',file=output)

# Retrieve the value written.
print(output.getvalue())

output.close()   # Discard buffer memory.

# Initialize a read buffer.
input = io.StringIO('Inital value for read buffer')

# Read from the buffer.
print(input.read())

这个例子使用了read(),不过也可以用readline()和readlines()方法。StringIO类还提供了一个seek()方法,读取文本时可以在缓冲区中跳转,如果使用一种前向解析算法则这个方法对于回转很有用。
运行结果:
在这里插入图片描述

要处理原始字节而不是Unicode文本,可以使用BytesIO。

import io

# write to a buffer.
output = io.BytesIO()
output.write('This goes into the buffer. '.encode('utf-8'))
output.write('áçÉ'.encode('utf-8'))

# Retrieve the value written.
print(output.getvalue())

output.close()  # Discard buffer memory.

# Initialize a read buffer.
input = io.BytesIO(b'Inital value for read buffer')

# Read from the buffer.
print(input.read())

写入BytesIO实例的值一定是bytes而不是str。
运行结果:

b’This goes into the buffer. \xc3\xa1\xc3\xa7\xc3\x89’
b’Inital value for read buffer’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值