Python:18.StringIO和BytesIO

2018-07-12  本文已影响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())
上一篇 下一篇

猜你喜欢

热点阅读