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