Maison > Article > développement back-end > python模块之StringIO使用示例
StringIO经常被用来作为字符串的缓存,应为StringIO有个好处,他的有些接口和文件操作是一致的,也就是说用同样的代码,可以同时当成文件操作或者StringIO操作。比如:
def writedata(fd, msg):
fd.write(msg)
f = open('aaa.txt', 'w')
writedata(f, "xxxxxxxxxxxx")
f.close()
s = StringIO.StringIO()
writedata(s, "xxxxxxxxxxxxxx")
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