Python 7.2 StringIO和BytesIO
2016-01-27 12:04
676 查看
StringIO和BytesIO
StringIO
很多时候,数据读写不一定是文件,也可以在内存中读写。
StringIO顾名思义就是在内存中读写str。
要把str写入StringIO,我们需要先创建一个StringIO,然后像文件一样写入就可:
>>>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
StringIO只能操作str,如果要操作二进制数据,就需要BytesIO
BytesIO实现了内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:
>>>from io import BytesIO
>>>f =BytesIO()
>>>f.write('中文'.encode('utf-8'))
6
>>>print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
请注意,写的不是str,而是经过UTF-8编码的bytes。
和StringIO类似,可以用一个bytes初始化BytesIO,然后像文件一样读取:
>>>from io import BytesIO
>>>f =BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>>f.read()
b'\xe4\xb8\xad\xe6\x96\x87'
小结:
StringIO和BytesIO是内存中操作str和bytes的方法,使得读写文件具有一致的接口。
StringIO
很多时候,数据读写不一定是文件,也可以在内存中读写。
StringIO顾名思义就是在内存中读写str。
要把str写入StringIO,我们需要先创建一个StringIO,然后像文件一样写入就可:
>>>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
StringIO只能操作str,如果要操作二进制数据,就需要BytesIO
BytesIO实现了内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:
>>>from io import BytesIO
>>>f =BytesIO()
>>>f.write('中文'.encode('utf-8'))
6
>>>print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
请注意,写的不是str,而是经过UTF-8编码的bytes。
和StringIO类似,可以用一个bytes初始化BytesIO,然后像文件一样读取:
>>>from io import BytesIO
>>>f =BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>>f.read()
b'\xe4\xb8\xad\xe6\x96\x87'
小结:
StringIO和BytesIO是内存中操作str和bytes的方法,使得读写文件具有一致的接口。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法