[笔记]python的StringIO与BytesIO模块

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’

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务