博客
关于我
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报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>