7.5. StringIO — Read and write strings as files

该模块实现一个类似文件的类StringIO,它读取和写入字符串缓冲区(也称为内存文件)。请参阅文件对象的操作说明(文件对象)。(For standard strings, see str and unicode.)

class StringIO.StringIO([buffer])

当创建一个StringIO对象时,它可以通过将该字符串传递给构造函数来初始化为现有的字符串。如果没有字符串,则StringIO将开始为空。在这两种情况下,初始文件位置从零开始。

StringIO对象可以接受Unicode或8位字符串,但混合两者可能需要小心。如果两者都使用,那么不能被解释为7位ASCII(使用第8位)的8位字符串将导致getvalue()引发UnicodeError叫做。

以下 StringIO对象的方法需要特别提及:

StringIO.getvalue()

在调用StringIO对象的close()方法之前,随时检索“文件”的全部内容。See the note above for information about mixing Unicode and 8-bit strings; such mixing can cause this method to raise UnicodeError.

StringIO.close()

释放内存缓冲区。Attempting to do further operations with a closed StringIO object will raise a ValueError.

Example usage:

import StringIO

output = StringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()

7.6. cStringIO — Faster version of StringIO

cStringIO模块提供了和 StringIO 模块类似的一些接口。使用这个模块中的 function StringIO()StringIO.StringIO 对象更加的有效率。

cStringIO.StringIO([s])

返回一个类似 StringIO 的流,用来读写。

由于这是一个返回内建类型的工厂函数,所以你不能够通过继承它来实现自己想要的功能。也不能给它设置属性。但是可以在模块 StringIO 中,可以那样使用。

StringIO 模块不同的是,这个模块不接受 不能被转化成 plain ASCII 字符的 Unicode。

另一个与 StringIO 模块不同就是,当调用 StringIO() 时,如果传入了字符串参数,那么它将返回一个 read-only object。如果传入了字符参数,返回的 object 就没有 write 方法。These objects are not generally visible. They turn up in tracebacks as StringI and StringO.

The following data objects are provided as well:

cStringIO.InputType

The type object of the objects created by calling StringIO() with a string parameter.

cStringIO.OutputType

The type object of the objects returned by calling StringIO() with no parameters.

这个模块还有一个C API。请参阅模块来源了解更多信息。

Example usage:

import cStringIO

output = cStringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()