博客
关于我
StringIO和BytesIO
阅读量:494 次
发布时间:2019-03-07

本文共 968 字,大约阅读时间需要 3 分钟。

数据读写的两种方式分析 数据读写不仅限于文件,内存中也可以进行读写操作。这种操作方式有两种主流实现:一种是基于字符的读写(StringIO),另一种是基于字节的读写(BytesIO)。

StringIO的应用场景 StringIO 创建的对象可以用来在内存中读写字符串。写入操作类似于向文件中写入,只需调用write方法并传入字符串即可。读取操作通常采用readline或getvalue方法来获取完整的字符串内容。 常见的使用场景是处理文本数据,尤其是需要频繁读写或者不确定大小的文本文件。

from io import StringIO          f_w = StringIO()          f_w.write('hello')          f_w.write(' ')          f_w.write('world!')          print(f_w.getvalue())          #输出: hello world!          f_r = StringIO('Hello!\nHi!\nGoodbye!')          while True:            s = f_r.readline()            if s == '':                break            print(s.strip())

BytesIO的应用场景 BytesIO 创建的对象用于内存读写操作,处理的是二进制数据。写入操作需要先将数据转换为字节类型(如使用encode方法),读取操作则直接返回字节数据。 常见的应用场景是处理二进制文件,如图片加载器或者压缩解压文件编码解码等。

from io import BytesIO          f_w = BytesIO()          f_w.write('中文'.encode('utf-8'))          print(f_w.getvalue())          #输出: b'\x4b\x8c\xad\x6f\x87'          f_r = BytesIO(b'\x4b\x8c\xad\x6f\x87')          print(f_r.read())

转载地址:http://ryicz.baihongyu.com/

你可能感兴趣的文章
Python: Range() 最大尺寸;动态的还是静态的?
查看>>
Python: Windows下用 multiprocessing 的深坑
查看>>
python:Could not find platform independent libraries <prefix>解决方法
查看>>
Python:datetime tzinfo 时区名称文档
查看>>
Python:deepcopy(list) vs new_list = old_list[:]
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
查看>>
Python:TypeError:无法连接“str“和“int“对象
查看>>
Python:XPath 在 ElementTree 中不可用
查看>>
Python:从 FTP 服务器下载文件
查看>>
python:从列表中创建元组列表
查看>>
Python:从嵌套列表中删除重复项
查看>>
Python:从间隔映射到值
查看>>
Python:使用 shell=False 的子进程调用不起作用
查看>>
Python:修改 PATH 环境变量的平台无关方式
查看>>
Python:假与 0
查看>>
Python:函数使用
查看>>
Python:函数进阶
查看>>
Python:在整数的二进制表示中查找最长的二进制间隙
查看>>