美文网首页
Python:18.StringIO和BytesIO

Python:18.StringIO和BytesIO

作者: 许瘦子来世 | 来源:发表于2018-07-12 11:31 被阅读7次
# 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())

相关文章

网友评论

      本文标题:Python:18.StringIO和BytesIO

      本文链接:https://www.haomeiwen.com/subject/anblpftx.html