python模块之StringIO
2007-06-18 10:52
288 查看
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属性。
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属性。
相关文章推荐
- Python StringIO模块实现在内存缓冲区中读写数据
- python模块之StringIO
- [置顶] 【python StringIO模块】感受内存文件的速度优势
- Python小模块--StringIO
- Python StringIO模块 实现在内存缓冲区中读写数据
- python模块之StringIO
- Python的StringIO模块和cStringIO模块
- python的StringIO模块
- python模块之StringIO
- python中的StringIO模块——html
- Python模块之StringIO【转】
- python模块之StringIO
- python中的StringIO模块
- Python模块之StringIO
- Python StringIO模块(或Six.BytesIO()模块)实现在内存缓冲区中读写数据
- python中的StringIO模块
- Python 标准库 -> StringIO模块 And cStringIO模块
- python中的StringIO模块
- [笔记]python的StringIO与BytesIO模块
- python模块—StringIO and BytesIO