博客
关于我
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中del函数的垃圾回收
查看>>
Python中DrissionPage的详细解析与实战
查看>>
python中enumerate、变量类型转换
查看>>
python中execute是啥_python – 为什么“c.execute(…)”打破循环?
查看>>
python中exit和break区别_Python中exit()和sys.exit()之间的区别
查看>>
python中h5的用法
查看>>
python中http协议编程_HTTP编程
查看>>
python中if的效率_python中关于if-else使用性能的一点感悟
查看>>
python中import os_Python:相对导入与绝对导入(import)、os.path、__file__
查看>>
python中is和==操作符
查看>>
python中range()函数的返回值是多少?
查看>>
Python中range对象的使用以及打印九九乘法表
查看>>
Python中reshape函数参数-1的意思?
查看>>
Python中set.discard和set.remove方法之间的运行时差异?
查看>>
Python接口自动化测试企业级实战
查看>>
python中tkinter中value_输入字段中的python Tkinter get()值
查看>>
Python中wx.FlexGridSizer
查看>>
Python中xPath技术和BeautifulSoup的使用
查看>>
python中yield的用法详解——最简单,最清晰的解释
查看>>
python中‘set.intersection()‘的算法是什么?
查看>>