7.5. StringIO —以文件形式读取和写入字符串
该模块实现了类似文件的类StringIO,该类读取和写入字符串缓冲区(也称为内存文件)。请参阅文件对象的说明以进行操作(第File Objects节)。 (有关标准字符串,请参见str和unicode。)
-
- class *
StringIO.
StringIO
([* buffer *])
- class *
StringIO对象可以接受 Unicode 或 8 位字符串,但是将两者混合使用可能会有些麻烦。如果两者都使用,则不能解释为 7 位 ASCII(使用第 8 位)的 8 位字符串将导致在调用getvalue()时引发UnicodeError。
StringIO对象的以下方法需要特别提及:
-
StringIO.
getvalue
( )- 在调用StringIO对象的close()方法之前,可以随时检索“文件”的全部内容。有关混合 Unicode 和 8 位字符串的信息,请参见上面的 Comments。这种混合会导致此方法提高UnicodeError。
-
StringIO.
close
( )- 释放内存缓冲区。try对关闭的StringIO对象执行进一步的操作将引发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 — StringIO 的更快版本
cStringIO模块提供的接口与StringIO模块相似。pass使用此模块中的函数StringIO(),可以更有效地使用StringIO.StringIO对象。
cStringIO.
StringIO
([* s *])- 返回类似 StringIO 的流以进行读取或写入。
由于这是一个工厂函数,它返回内置类型的对象,因此无法使用子类构建自己的版本。无法在其上设置属性。在这种情况下,请使用原始的StringIO模块。
与StringIO模块不同,此模块不能接受无法编码为纯 ASCII 字符串的 Unicode 字符串。
与StringIO模块的另一个区别是,使用字符串参数调用StringIO()会创建一个只读对象。与没有字符串参数创建的对象不同,它没有写方法。这些对象通常是不可见的。它们在回溯中显示为StringI
和StringO
。
还提供了以下数据对象:
-
cStringIO.
InputType
- pass使用字符串参数调用StringIO()创建的对象的类型对象。
-
cStringIO.
OutputType
- pass不带参数调用StringIO()返回的对象的类型对象。
该模块也有一个 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()