冲扬心法

笑声激发自强,发愤、图强、飞身向上

   :: 首页  ::  ::  ::  :: 管理

主要介绍python两个内存读写IO:StringIO和BytesIO,使得读写文件具有一致的接口

StringIO

内存中读写str。需要导入StringIO

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('I O U')
5
>>> f.getvalue()
'I O U'

也可以用一个str初始化StringIO,然后像读文件一样读取:

>>> from io import StringIO
>>> f = StringIO('wc\nlove\nLY')
>>> while 1:
...     s = f.readline()
...     if s =='':
...             break
...     print(s.strip())
...
wc
love
LY

BytesIO

内存中操作二进制数据:

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('武松'.encode('utf-8'))
6
>>> f.read()
b''
>>> f.getvalue()
b'wc\xe6\xad\xa6\xe6\x9d\xbe'

细心的童鞋会发现,f.read()竟然为空?!

这是因为stream position的原因。可以理解为IO的指针位置,可以使用tell()方法获得该值:

>>> d = StringIO('hehe')
>>> d.tell()
0
>>> d.read()
'hehe'
>>> d.tell()
4
>>> d.read()
''
>>> d.getvalue()
'hehe'

当拟调用诸如read()、readline()、getvalue()方法时,stream position的值是在变化的!当你读取完所有的内容后,指针的位置已经在最后了,此时你再调用read()方法时就为空了。但是可以使用d.getvalue()方法查看内容。

这时如何调用read()使得结果如我所愿呢,可以结合seek()方法,该方法会重置指针的位置:

>>> d.seek(3)
3
>>> d.read()
'e'
>>> d.seek(1)
1
>>> d.read()
'ehe'

 

posted on 2018-03-20 21:59  风雨一肩挑  阅读(757)  评论(0编辑  收藏  举报