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

python模块之StringIO使用示例

2018-10-12 13:50 866 查看

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: