7.12. io — 文本、二进制和原生流的 i/o 工具 | 文件系统 |《python 3 标准库实例教程》| python 技术论坛-380玩彩网官网入口
目的:实现文件 i / o ,并提供使用类文件 api 处理缓冲区的类。
io
模块实现了解释器内置的open()
后面的类,用于基于文件的输入和输出操作。这些类以这种方式进行分解,以便可以将它们重新组合以实现其他目的,例如,将 unicode 数据写入网络套接字。
内存流
stringio
提供了使用文件 api (read()
,write()
等)处理内存中的文本。在某些情况下,使用 stringio
构建大型字符串可以比其他字符串连接技术节省性能。内存中的流缓冲区对测试也是很有用的,因为写入磁盘上的真实文件可能会降低测试套件的速度。
这里有一些使用 stringio
缓冲区的标准例子:
io_stringio.py
import io
# 写入缓冲区
output = io.stringio()
output.write('this goes into the buffer. ')
print('and so does this.', file=output)
# 得到写入的值
print(output.getvalue())
output.close() # discard buffer memory
# 初始化一个读缓冲区
input = io.stringio('inital value for read buffer')
# 从缓冲区读
print(input.read())
这个例子使用了 read()
,但是 readline()
和 readlines()
方法也是可用的。stringio
也提供了一个 seek()
方法,用于在读取时在缓冲区跳转,如果使用预读分析算法,这对于倒带会很有用。
$ python3 io_stringio.py
this goes into the buffer. and so does this.
inital value for read buffer
如果要处理原生字节而不是 unicode 文本,使用 bytesio
。
io_bytesio.py
import io
# 写入一个缓冲区
output = io.bytesio()
output.write('this goes into the buffer. '.encode('utf-8'))
output.write('áçê'.encode('utf-8'))
# 获取写入的值
print(output.getvalue())
output.close() # discard buffer memory
# 初始化一个读缓冲区
input = io.bytesio(b'inital value for read buffer')
# 从缓冲区读
print(input.read())
写入 bytesio
的值必须是 bytes
而不是 str
。
$ python3 io_bytesio.py
b'this goes into the buffer. \xc3\x81\xc3\x87\xc3\x8a'
b'inital value for read buffer'
包装文本数据的字节流
诸如诸如套接字之类的原始字节流可以包装以处理字符串编码和解码,从而使他们更容易和文本数据一起使用。textiowrapper
类支持读写操作。write_through
参数禁用缓冲区,并立即将写入包装器的所有数据刷新到底层缓冲区。
io_textiowrapper.py
import io
# 写入一个缓冲区
output = io.bytesio()
wrapper = io.textiowrapper(
output,
encoding='utf-8',
write_through=true,
)
wrapper.write('this goes into the buffer. ')
wrapper.write('áçê')
# 获取写入的值
print(output.getvalue())
output.close() # discard buffer memory
# 初始化一个读缓冲区
input = io.bytesio(
b'inital value for read buffer with unicode characters '
'áçê'.encode('utf-8')
)
wrapper = io.textiowrapper(input, encoding='utf-8')
# 读取缓冲池
print(wrapper.read())
这个例子使用了一个 bytesio
实例作为流。 ,, 和 的示例演示了如何使用 textiowrapper
和其他类型的类文件对象。
$ python3 io_textiowrapper.py
b'this goes into the buffer. \xc3\x81\xc3\x87\xc3\x8a'
inital value for read buffer with unicode characters áçê
推荐阅读
- -- 使用
textiowrapper
的detach()
从封装的套接字中分别管理封装器。- -- 检查组合字符串及其相对优点的各种方法。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 cc 协议,如果我们的工作有侵犯到您的权益,请及时联系380玩彩网官网入口。