Python file-like object

open()函数返回的这种有个read()方法的对象,在Python中统称为file-like Object。除了file外,还可以是内存的字节流,网络流,自定义流等等。file-like Object不要求从特定类继承,只要写个read()方法就行。

StringIO BytesIO就是在内存中创建的file-like Object,常用作临时缓冲。

StringIO 和 BytesIO

很多时候,数据读写不一定是文件,也可以在内存中读写。要想在内存中对数据进行读写,就要使用到StringIOBytesIO了。前者是对字符串数据的读写,后者是对二进制数据的读写。

注意:如果write 后要马上 read() 需要先 seek(0),否则读取不到数据

(1)StringIO读写字符串数据

from io import StringIO

# 向内存中写入字符串数据
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world')

# getvalue()方法用于获取上述写入的数据
print(f.getvalue()) # 'hello world'
from io import StringIO

# 在内存中,初始化字符串数据
f = StringIO('Hello World')
# 从内存中读取数据
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip()) # 'Hello World'

(2)BytesIO读写二进制数据

from io import BytesIO

# 向内存中写入二进制数据
f = BytesIO()
f.write('中文'.encode('utf-8'))

# 打印结果是二进制数据
print(f.getvalue()) # b'\xe4\xb8\xad\xe6\x96\x87'
from io import BytesIO

# 在内存中初始化二进制数据
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')

# 读取、并打印二进制数据
print(f.read()) # b'\xe4\xb8\xad\xe6\x96\x87'

你可能感兴趣的:(Python file-like object)