# -*- coding: utf-8 -*-
#StringIO
#如何用类似文件读写的方法在内存中读写str(可以使接口统一)
from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('Hello')
print(f.getvalue())
s = f.readline() #StringIO要么用来读read(),要么用来写write(),不能同时用,这里不会出结果
print(s)
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.read()
if s == '':
break
print(s.strip())
#BytesIO
#StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
廖雪峰python学习笔记12.StringIO和BytesIO
最新推荐文章于 2025-02-15 20:04:29 发布