StringIO

StringIO 模块的使用. 它实现了一个工作在内存的文件对象 (内存文件).

在大多需要标准文件对象的地方都可以使用它来替换.

-------------------------------------------------------------------------------------

 使用 StringIO 模块从内存文件读入内容

-------------------------------------------------------------------------------------

import StringIO

MESSAGE = "abcdefg"

file = StringIO.StringIO(MESSAGE)   # 将MESSAGE内容写入到内存中,并返回file类型到file变量

print file.read()                                  # 读取内存文件内容 

 

-------------------------------------------------------------------------------------

使用 StringIO 模块向内存文件写入内容

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

-------------------------------------------------------------------------------------

file = StringIO.StringIO()
file.write("This man is no ordinary man. ")  # 将内容写入到内存
file.write("This is Mr. F. G. Superman.")   # 将内容写入到内存
print file.getvalue()                                   # 输出file内存内容

-------------------------------------------------------------------------------------

使用 StringIO 模块捕获输出

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

-------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------

你可能感兴趣的:(python,StringIO)