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屬性。