首页 > 其他 > 详细

StringIO和BytesIO

时间:2019-09-11 20:32:24      阅读:97      评论:0      收藏:0      [点我收藏+]

StringIO:在内存中读写str

>>> from io import StringIO
>>> f = StringIO()
>>> f.write(hello)
5
>>> f.write( )
1
>>> f.write(world!)
6
>>> print(f.getvalue())
hello world!
getvalue():方法用于获得写入后的str。

要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:
>>> from io import StringIO
>>> f = StringIO(Hello!\nHi!\nGoodbye!)
>>> while True:
...     s = f.readline()
...     if s == ‘‘:
...         break
...     print(s.strip())
...
Hello!
Hi!
Goodbye!

BytesIO:在内存中读写bytes

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write(中文.encode(utf-8))
6
>>> print(f.getvalue())
b\xe4\xb8\xad\xe6\x96\x87

 

 

StringIO和BytesIO

原文:https://www.cnblogs.com/BeautifulWorld/p/11507758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!