说明

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

例子

  1. 从内存文件读入内容

    1. from io import StringIO
    2. message = 'That man is depriving a village somewhere of a computer scientist.'
    3. file = StringIO(message)
    4. print(file.read())
    5. >>That man is depriving a village somewhere of a computer scientist.
  2. 使用getvalue方法用来返回内部的字符串值

    1. from io import StringIO
    2. file = StringIO()
    3. file.write("This man is no ordinary man.")
    4. print(file.getvalue())
    5. >>This man is no ordinary man.
  3. 使用StringIO捕获输出

    1. from io import StringIO
    2. import sys
    3. s1 = '23131'
    4. n = 12
    5. v = 13
    6. old_stdout = sys.stdout
    7. file = StringIO()
    8. sys.stdout = file
    9. print(s1,n,v)
    10. sys.stdout = old_stdout
    11. print(file.getvalue())
    12. >>23131 12 13

    cStringIO


是一个可选的模块, 是 StringIO 的更快速实现. 它的工作方式和 StringIO 基本相同, 但是它不可以被继承,在python3中被废除

  1. import cStringIO
  2. MESSAGE = "That man is depriving a village somewhere of a computer scientist."
  3. file = cStringIO(MESSAGE)
  4. print(file.read())