当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3标准库:io文本、十进制和原始流I/O工具

Python3标准库:io文本、十进制和原始流I/O工具

2020年03月21日  | 移动技术网IT编程  | 我要评论

老爸向前冲演员表,犹大的烟,三优客

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

要处理原始字节而不是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。

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。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网