1 | # coding=gbk |
2 | |
3 | import StringIO , cStringIO , sys |
4 | |
5 | s = StringIO . StringIO ( " JGood is a handsome boy " ) |
6 | s . write ( " JGood is a handsome boy /r/n " ) |
7 | s . write ( ' okkkk中国 ' ) |
8 | s . seek ( 0 ) |
9 | print s . read ( ) |
10 | |
11 | # 最后4个字节 |
12 | s . seek ( - 4 , 2 ) |
13 | print s . read ( ) |
14 | |
15 | # ---- 结果 ---- |
16 | # JGood is a handsome boy |
17 | # okkkk中国 |
18 | # 中国 |
通过例子,我们看到了StringIO的行为,基本与file一致。StringIO提供了一个方法,可以方便的获取其中的数据:StringIO. getvalue()。如果使用read方法获取其中的数据,必须通过seek先设置"文件指针"的位置。
Python标准模块中还提供了一个cStringIO模块,它的行为与StringIO基本一致,但运行效率方面比StringIO更好。但使用 cStringIO模块时,有几个注意点: 1. cStringIO.StringIO不能作为基类被继承;2. 创建cStringIO.StringIO对象时,如果初始化函数提供了初始化数据,新生成的对象是只读的。所以下面的代码是错误的:s = cStringIO.StringIO("JGood/n"); s.write("OOOKKK");
补充的部分:
StringIO经常被用来作为字符串的缓存,因为StringIO有个好处,他的有些接口和文件操作是一致的,也就是说用同样
的代码,可以同时当成文件 操作或者StringIO操作。比如:
import string, os, sys
import StringIO
def writedata(fd, msg):
fd.write(msg)
f = open('aaa.txt', 'w')
writedata(f, "xxxxxxxxxxxx")
f.close()
s = StringIO.StringIO()
writedata(s, "xxxxxxxxxxxxxx")
因为文件对象和StringIO大部分的方法都是一样的,比如read, readline, readlines, write, writelines都是有的,
这样,StringIO就可以非常方便的作为"内存文件对象"。
import string
import StringIO
s = StringIO.StringIO()
s.write("aaaa")
lines = ['xxxxx', 'bbbbbbb']
s.writelines(lines)
s.seek(0)
print s.read()
print s.getvalue()
s.write(" ttttttttt ")
s.seek(0)
print s.readlines()
print s.len
StringIO还有一个对应的c语言版的实现,它有更好的性能,但是稍有一点点的区别,cStringIO没有len和pos属性。
另一种用法就是:
在web server开发中,先用f把需要的html内容写进f,然后一次copy输出到self.wfile。
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
f.write("<hr>\n<ul>\n")
f.seek(0)
if f:
self.copyfile(f, self.wfile) #copy all the contents to the self.wfile
f.close()