Python3中io文本及原始流I/O工具怎么用

发布时间:2021-06-04 15:01:54 作者:小新
来源:亿速云 阅读:161

这篇文章给大家分享的是有关Python3中io文本及原始流I/O工具怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

1.1 内存中的流

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

下面是使用StringIO缓冲区的一些标准例子。

import io
# Writing 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()方法,读取文本时可以在缓冲区中跳转,如果使用一种前向解析算法,则这个方法对于回转很有用。

Python3中io文本及原始流I/O工具怎么用

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

import io
# Writing 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。

Python3中io文本及原始流I/O工具怎么用

1.2 为文本数据包装字节流

原始字节流(如套接字)可以被包装为一个层来处理串编码和解码,从而可以更容易地用于处理文本数据。TextIOWrapper类支持读写。write_through参数会禁用缓冲,并且立即将写至包装器的所有数据刷新输出到底层缓冲区。

import io
# Writing 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 memory
 
# 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。

Python3中io文本及原始流I/O工具怎么用

感谢各位的阅读!关于“Python3中io文本及原始流I/O工具怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. ubunt18.04LTS+vscode+anaconda3下的python+C++调试方法
  2. python 如何用pandas同时对多列进行赋值

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:mysql中update语句的示例分析

下一篇:Python类和实例的属性机制原理是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》