Python StringIO与cStringIO

StringIO的行为与file对象非常像,但它不是磁盘上文件,而是一个内存里的“文件”,我们可以将操作磁盘文件那样来操作StringIO。一个简单的例子,让你对StringIO有一个感性的认识:
# coding=gbk
 
import   StringIO ,   cStringIO ,   sys
 
s   =   StringIO . StringIO ( " JGood   is   a   handsome   boy " )
s . write ( " JGood   is   a   handsome   boy   /r/n " )
s . write ( ' okkkk中国 ' )
s . seek ( 0 )
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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值