欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python IO编程之(stringIO与BytesIO)

程序员文章站 2022-06-25 19:08:14
StringIO数据读写不一定是文件,也可以在内存中读写。StringIO顾名思义就是在内存中读写str。要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:from io import StringIO #调用模块f = StringIO() #创建一个StringIOf.write('hello') #将hello写入StringIOf.write(' ')f.write('world!')print(f.getvalue())...

StringIO

数据读写不一定是文件,也可以在内存中读写。StringIO顾名思义就是在内存中读写str。

要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:

from io import StringIO     #调用模块
f = StringIO()     #创建一个StringIO
f.write('hello')  #将hello写入StringIO
f.write(' ')
f.write('world!')
print(f.getvalue())  #获取StringIO写入后的str

python  IO编程之(stringIO与BytesIO)

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

from io import StringIO   
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip())

python  IO编程之(stringIO与BytesIO)

BytesIO

BytesIO命令可以操作二进制数据。

BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:

from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())  #获取BytesIO写入后的二进制数据

python  IO编程之(stringIO与BytesIO)

注意,写入的不是str,而是经过UTF-8编码的bytes。

和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:

from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read()
print(f.getvalue())  #获取BytesIO写入后的二进制数据

python  IO编程之(stringIO与BytesIO)
小结
StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。

本文地址:https://blog.csdn.net/weixin_49198853/article/details/110692981

相关标签: python