StringIO和BytesIO

StringIO和BytesIO

StringIO和BytesIO

StringIO

在内存中读写str,要把str写入stringIO,需要先创建一个StringIO,然后像文件一样写入即可:

getvalue():获取写入后的str

from io import StringIO
f = StringIO()  # 先实例化一个对象
f.write('hello')  # 字符个数为5
f.write(' ')  # 字符个数为1
f.write('word')  # 字符个数为1
print(f.getvalue())  # hello word

要读取StringIO,可以用一个str初始化StringIO,然后像读文件一样读取:

from io import StringIO
from io import StringIO
f = StringIO('hello\nhi\ngoodbye\n')  # 先实例化一个对象
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip())
# hello
# hi
# goodbye

BytesIO

在内存中读写二进制数据,BytesIO实现了内存中读写bytes,需要创建BytesIO,然后写入bytes:

from io import BytesIO
f = BytesIO()
f.write('上课不要睡觉'.encode('utf-8'))  # 写入的不是str,而是utf-8编码的bytes类型
print(f.getvalue())
# b'\xe4\xb8\x8a\xe8\xaf\xbe\xe4\xb8\x8d\xe8\xa6\x81\xe7\x9d\xa1\xe8\xa7\x89'

用一个bytes初始化BytesIO,然后像读文件一样读取:

from io import BytesIO
f = BytesIO(b'\xe4\xb8\x8a\xe8\xaf\xbe\xe4\xb8\x8d\xe8\xa6\x81\xe7\x9d\xa1\xe8\xa7\x89')
data = f.read()
print(data.decode('utf-8'))  # 上课不要睡觉

StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。

posted @ 2022-09-17 14:58  努力努力再努力~W  阅读(76)  评论(0)    收藏  举报