StringIO 模块

它实现了一个工作在内存的文件对象 (内存文件). 在大多需要标准文件对象的地方都可以使用它来替换.

>>> import StringIO

>>> MESSAGE=”I am a king of england”

>>> file=StringIO.StringIO(MESSAGE)

>>> print file.read()

I am a king of england

StringIO 类实现了内建文件对象的所有方法, 此外还有 getvalue 方法用来返回它内部的字符串值.

>>>

>>> import StringIO

>>> file=StringIO.StringIO()

>>> file.write(“i am a king of england”)

>>> file.write(“and i am the farther of the england’s king”)

>>> print file.getvalue()

i am a king of englandand i am the farther of the england’s king

StringIO 可以用于重新定向 Python 解释器的输出:

>>> import StringIO

>>> import string,sys

>>> stdout=sys.stdout

>>> sys.stdout=file=StringIO.StringIO()

>>>

>>> print “””

… According to Gbaya folktales,trickery and guile

… are the best ways to defeat the python,king of snakes,

… which was hatched from a dragon at the world’s start.

… –National Geographic,May 1997

… “””

>>> sys.stdout=stdout

>>> print string.upper(file.getvalue())

ACCORDING TO GBAYA FOLKTALES,TRICKERY AND GUILE

ARE THE BEST WAYS TO DEFEAT THE PYTHON,KING OF SNAKES,

WHICH WAS HATCHED FROM A DRAGON AT THE WORLD’S START.

–NATIONAL GEOGRAPHIC,MAY 1997

通过StringIO模块 – yangwenchao1983的专栏 – 博客频道 – CSDN.NET.

- EOF -