IO编程-StringIO和BytesIO

2021-01-14  本文已影响0人  小飞船1号

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

1、StringIO

StringIO顾名思义就是在内存中读写str。
getvalue()方法用于获得写入后的str。

#1
from io import StringIO
f=StringIO()
f.write('hello')
f.write(' ')
f.write('world!!')
print(f.getvalue())
#hello world!!

#2
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
    s = f.readline()
    if s == '':
       break
    print(s.strip())
2、BytesIO

BytesIO实现了在内存中读写bytes

#1
from io import BytesIO
f=BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
#b'\xe4\xb8\xad\xe6\x96\x87'
#2
from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read()
上一篇下一篇

猜你喜欢

热点阅读