StringIO常常被用来做为字符串的缓存,应为StringIO有个好处,他的有些接口和文件操做是一致的,也就是说用一样的代码,能够同时当成文件操做或者StringIO操做。python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import
StringIO
s
=
StringIO.StringIO()
s.write(
'www.baidu.com\r\n'
)
s.write(
'news.realsil.com.cn'
)
s.seek(
0
)
print
'*'
*
20
print
s.tell()
print
s.read()
print
'*'
*
20
print
s.tell()
print
s.read()
print
'*'
*
20
print
s.tell()
print
s.getvalue()
print
'*'
*
20
print
s.tell()
s.seek(
-
4
,
2
)
print
s.read()
|
运行结果:web
********************
0
www.baidu.com
news.realsil.com.cn
********************
34缓存
********************
34
www.baidu.com
news.realsil.com.cn
********************
34
m.cn函数
----------------------
s.read([n])
参数n限定读取长度,int类型;缺省状态为从当前读写位置读取对象s中存储的全部数据。读取结束后,读写位置被移动。
----------------------
s.readline([length])
参数length限定读取的结束位置,int类型,缺省状态为None:从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
----------------------
s.readlines([sizehint])
参数sizehint为int类型,缺省状态为读取全部行并做为列表返回,除此以外从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
----------------------
s.write(s)
从读写位置将参数s写入给对象s。参数s为str或unicode类型。读写位置被移动。
----------------------
s.writelines(list)
从读写位置将list写入给对象s。参数list为一个列表,列表的成员为str或unicode类型。读写位置被移动。
----------------------
s.getvalue()
此函数没有参数,返回对象s中的全部数据。
----------------------
s.truncate([size])
从读写位置起切断数据,参数size限定裁剪长度,缺省值为None。
----------------------
s.tell()
返回当前读写位置。
----------------------
s.seek(pos[,mode])
移动当前读写位置至pos处,可选参数mode为0时将读写位置移动至pos处,为1时将读写位置从当前位置起向后移动pos个长度,为2时将读写位置置于末尾处再向后移动pos个长度;默认为0。
----------------------
s.close()
释放缓冲区,执行此函数后,数据将被释放,也不可再进行操做。
----------------------
s.isatty()
此函数老是返回0。不论StringIO对象是否已被close()。
----------------------
s.flush()
刷新内部缓冲区。
----------------------spa