博客
关于我
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/

你可能感兴趣的文章
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>