您的位置:首页 > 编程语言 > Python开发

Python StringIO与cStringIO

2012-08-20 15:08 405 查看
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 ( )
print   s . read ( )
10  
11 # 最后4个字节
12 s . seek ( - ,   )
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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息