说明
它实现了一个工作在内存的文件对象(内存文件). 在大多需要标准文件对象的地方都可以使用它来替换.
例子
从内存文件读入内容
from io import StringIOmessage = 'That man is depriving a village somewhere of a computer scientist.'file = StringIO(message)print(file.read())>>That man is depriving a village somewhere of a computer scientist.
使用getvalue方法用来返回内部的字符串值
from io import StringIOfile = StringIO()file.write("This man is no ordinary man.")print(file.getvalue())>>This man is no ordinary man.
使用StringIO捕获输出
from io import StringIOimport syss1 = '23131'n = 12v = 13old_stdout = sys.stdoutfile = StringIO()sys.stdout = fileprint(s1,n,v)sys.stdout = old_stdoutprint(file.getvalue())>>23131 12 13
cStringIO
是一个可选的模块, 是 StringIO 的更快速实现. 它的工作方式和 StringIO 基本相同, 但是它不可以被继承,在python3中被废除
import cStringIOMESSAGE = "That man is depriving a village somewhere of a computer scientist."file = cStringIO(MESSAGE)print(file.read())
