栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python StringIO及BytesIO包使用方法解析

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

f = StringIO(‘hellonworld!‘)
while True:
  s = f.readline()
  if s == ‘‘:
    break
  print(s.strip()) #去除n
#打印结果
hello
world!

BytesIO

想要操作二进制数据,就需要使用BytesIO。

当然包括视频、图片等等。

from io import BytesIO

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

print(f.getvalue())
#打印结果
b‘xe4xbfx9dxe5xadx98xe4xb8xadxe6x96x87‘

请注意,写入的不是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())

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/18689.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号