StringIO和BytesIO

1. StringIO

很多时候,数据读写不一定是文件,也可以在内存中读写。

StringIO顾名思义就是在内存中读写str。

要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:

from _io import StringIO
str_io = StringIO()

# str_io 写入内容
str_io.write('hello')
str_io.write(' ')
#str_io.write(12)    #操作对象只能是str,同C/C++
str_io.writelines('world!')

print(str_io.getvalue())

str_io = StringIO('1\n2\n3\n4\n5!')
# str_io.write('1\n2\n3\n4\n5!')
while True:
    s = str_io.readline()
    if s=='':
        break;
    print(s.strip())

注意:

getvalue()方法用于获得写入后的str。

要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取

 

2. BytesIO

StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。

BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:

from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())

结果
-----------------------------------
b'\xe4\xb8\xad\xe6\x96\x87'

请注意,写入的不是str,而是经过UTF-8编码的bytes

和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:

from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read()   # 读到结果 b'\xe4\xb8\xad\xe6\x96\x87'

3. 小结

StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口.

 

转载自:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431918785710e86a1a120ce04925bae155012c7fc71e000

转载于:https://www.cnblogs.com/AbcFly/p/6242398.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值