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

你可能感兴趣的文章
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>