python : StringIO 和 BytesIO:
--数据读写不一定是文件,也可以在内存中读写
StringIO:
顾名思义就是在内存中读写str。
from io import StringIO
f= StringIO()
f.write('')
---》f.getvalue()
--StringIO操作的只能是str!!
--读取StringIO,用一个str初始化StringIO,像读文件一样读取
BytesIO:
要操作二进制数据,就需要使用BytesIO。
BytesIO实现了在内存中读写bytes
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
... s = f.readline()
... if s == '':
... break
... print(s.strip())
总结:
StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步