Python:18.StringIO和BytesIO

# StringIO
'''
1. 在内存中读取str。只能操作str
2. getvalue()方法用于获得写入后的str
'''
from io import StringIO

f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())

ff = StringIO('Hello\nHi!\nGoodbye!')
while True:
    s = ff.readline()
    if s == '':
        break
    print(s.strip())

# BytesIO
'''
1. 操作二进制数据
'''
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())

ff = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(ff.read())
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容