[笔记]python的StringIO与BytesIO模块
来源:互联网 发布:中国税务网络大学平台 编辑:程序博客网 时间:2024/06/06 08:29
StringIO
StringIO就是在内存中读写字符串,要把字符串读入内存,要先创建StringIO实例,然后像写入文件一样,将字符串写入这个实例即可。
>>> from StringIO import StringIO
>>> memory = StringIO()
>>> memory.write(‘hello’)
>>> memory.write(’ ‘)
>>> memory.write(‘world’)
>>> memory.getvalue()
‘hello world’
StringIO.getvalue()可以返回StringIO实例中的字符串。
如果要读取StringIO的字符串可以使用与文件类似的read,readline ,readlines等方法。
>>> memory.write(‘\n new line \n’)
>>> memory.seek(0) # 回到文件最开头
>>> for line in memory:
print line
hello world
new line
或者利用readline函数:
>>> memory.seek(0)
>>>
while True: s = memory.readline() if s == '': break print(s.strip())
hello world
new line
BytesIO
我们在读写文件时也有时利用二进制数据进行读取。
而StringIO只能读取字符串到内存,这时候,就需要BytesIO模块进行操作。
>>> from io import BytesIO
>>> a = unicode(‘你好世界!’,’gbk’)
>>> memory = BytesIO()
>>> memory.write(a.encode(‘utf8’))
15L
>>> print(memory.getvalue())
‘你好世界!’
>>> memory.seek(0)
0L
>>> memory.read()
‘\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81’
>>> a.encode(‘utf8’)
‘\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81’
- [笔记]python的StringIO与BytesIO模块
- python StringIO和BytesIO
- python StringIO和BytesIO
- Python StringIO和BytesIO
- StringIO与BytesIO
- 廖雪峰python学习笔记12.StringIO和BytesIO
- python学习笔记(十五)标准库StringIO和BytesIO
- Python基础-StringIO和BytesIO
- Python StringIO模块(或Six.BytesIO()模块)实现在内存缓冲区中读写数据
- python学习——StringIO和BytesIO
- python入门笔记(Day8)--StringIO,BytesIO,环境变量, 操作文件和目录
- Python笔记-IO同步和异步、 读写文件、StringIO和BytesIO
- Python基础-内存读数据StringIO和BytesIO
- StringIO和BytesIO
- StringIO和BytesIO
- StringIO 跟 BytesIO
- stringIO 和 BytesIO
- StringIO和BytesIO
- 程序员是否必须会算法
- Java 内存区域和GC机制
- VC++某些笔记
- HDU ACM 1080 Human Gene Functions
- 小九扑克怎样控牌∑▄【在线演示QQ:194714506】
- [笔记]python的StringIO与BytesIO模块
- DDD初学指南
- 小九扑克控牌绝技▂∩【在线演示QQ:194714506】
- 二级指针
- Java语言描述:回溯法之01背包问题(最易理解的回溯法讲解)
- 等于还是不等于?
- @Override用在哪儿
- mysql 分页limit 优化
- 小九扑克能控牌吗▂↑【在线演示QQ:194714506】