如何高效运用Python的StringIO和BytesIO包实现数据流操作?

2026-04-20 05:191阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计304个文字,预计阅读时间需要2分钟。

如何高效运用Python的StringIO和BytesIO包实现数据流操作?

`StringIO` 主要用于内存中的字符串读写。主要用法是:

pythonfrom io import StringIOf=StringIO()f.write('12345')print(f.getvalue())f.write('54321')f.write('abcde')print(f.getvalue())

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(‘hello\nworld!‘) while True: s = f.readline() if s == ‘‘: break print(s.strip()) #去除\n #打印结果 hello world!

BytesIO

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

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

如何高效运用Python的StringIO和BytesIO包实现数据流操作?

from io import BytesIO f = BytesIO() f.write(‘保存中文‘.encode(‘utf-8‘)) print(f.getvalue()) #打印结果 b‘\xe4\xbf\x9d\xe5\xad\x98\xe4\xb8\xad\xe6\x96\x87‘

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

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

本文共计304个文字,预计阅读时间需要2分钟。

如何高效运用Python的StringIO和BytesIO包实现数据流操作?

`StringIO` 主要用于内存中的字符串读写。主要用法是:

pythonfrom io import StringIOf=StringIO()f.write('12345')print(f.getvalue())f.write('54321')f.write('abcde')print(f.getvalue())

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(‘hello\nworld!‘) while True: s = f.readline() if s == ‘‘: break print(s.strip()) #去除\n #打印结果 hello world!

BytesIO

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

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

如何高效运用Python的StringIO和BytesIO包实现数据流操作?

from io import BytesIO f = BytesIO() f.write(‘保存中文‘.encode(‘utf-8‘)) print(f.getvalue()) #打印结果 b‘\xe4\xbf\x9d\xe5\xad\x98\xe4\xb8\xad\xe6\x96\x87‘

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

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