7.12. io — 文本、二进制和原生流的 I/O 工具

未匹配的标注

目的:实现文件 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 实例作为流。  bz2http.server, 和 subprocess 的示例演示了如何使用 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 ÁÇÊ

推荐阅读

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/pymotw/io-io-to...

译文地址:https://learnku.com/docs/pymotw/io-io-to...

上一篇 下一篇
讨论数量: 0
发起讨论 查看所有版本


暂无话题~