Python之io模块的使用

 IO模块的作用

IO模块在解脱器的内置open()之上实现了一些类来完成基于文件的输入和输出操作。

1、字符串的内存缓冲区创建和写入数据的示例

import io

# 创建一个字符串的内存缓冲区
output = io.StringIO()
output.write('This goes into the buffer')

# 打印到字符串内存缓冲区
print(' And so does this.', file=output)

# 从字符串内存缓冲区中获取值
print(output.getvalue())

# 初始化内存缓冲区,并且写入数据
input = io.StringIO('Inital value for read buffer')
print(input.read())
io_stringio.py

 测试效果

This goes into the buffer And so does this.

Inital value for read buffer

2、字节的内存缓冲区创建和写入数据的示例

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()

# 初始化字节内存缓冲区,并且写入数据
input = io.BytesIO(b'Inital value for read buffer')
print(input.read())
io_bytesio.py

测试效果

b'This goes into the buffer\xc3\x81\xc3\x87\xc3\x8a'
b'Inital value for read buffer'

3、给文本数据包装字节流的示例 

import io

# 在内存中创建字节缓冲区
output = io.BytesIO()

# 创建一个包装类,自动将字符串编辑为字节类型
# write_through : True,禁用缓冲
wrapper = io.TextIOWrapper(
    output,
    encoding='utf-8',
    write_through=True
)

# 往包装类,写入数据
wrapper.write('This goes into the buffer. ')
wrapper.write('ÁÇÊ')

# 获取缓冲区的数据
print(output.getvalue())

# 关闭缓冲区
output.close()

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())
io_textiowrapper.py

测试效果

b'This goes into the buffer. \xc3\x81\xc3\x87\xc3\x8a'
Inital value for read buffer with unicode characters ÁÇÊ
posted @ 2020-05-10 14:25  小粉优化大师  阅读(380)  评论(0编辑  收藏  举报