python模块之StringIO使用示例

WBOY
Release: 2016-06-10 15:15:55
Original
1318 people have browsed it

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属性。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template