python StringIO和BytesIO包的用法

StringIO

它主要是用在内存读写str中。

主要用法就是:

from io import StringIO

f = StringIO()
f.write('12345')
print(f.getvalue())

f.write('54321')
f.write('abcde')

print(f.getvalue())

#打印结果
12345
1234554321abcde
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

也可以使用str初始化一个StringIO然后像文件一样读取。

f = StringIO('hello
world!')
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip()) #去除

#打印结果
hello
world!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

BytesIO

想要操作二进制数据,就需要使用BytesIO。
当然包括视频、图片等等。

from io import BytesIO

f = BytesIO()
f.write('保存中文'.encode('utf-8'))

print(f.getvalue())
#打印结果
b'xe4xbfx9dxe5xadx98xe4xb8xadxe6x96x87'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

存放图片

f = BytesIO()

image_open = open('./1.jpg', 'rb')
f.write(image_open.read())

image_save = open('./2.jpg', 'wb')
image_save.write(f.getvalue())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
原文地址:https://www.cnblogs.com/tangda/p/13105725.html