5.6 字符串的I/O�作¶

问题¶

你想使用�作类文件对象的程���作文本或二进制字符串。

解决方案¶

使用 io.StringIO() 和 io.BytesIO() 类�创建类文件对象�作字符串数�。比如:

>>> s = io.StringIO()
>>> s.write('Hello World\n')
12
>>> print('This is a test', file=s)
15
>>> # Get all of the data written so far
>>> s.getvalue()
'Hello World\nThis is a test\n'
>>>

>>> # Wrap a file interface around an existing string
>>> s = io.StringIO('Hello\nWorld\n')
>>> s.read(4)
'Hell'
>>> s.read()
'o\nWorld\n'
>>>

io.StringIO �能用于文本。如果你��作二进制数�,�使用 io.BytesIO 类�代替。比如:

>>> s = io.BytesIO()
>>> s.write(b'binary data')
>>> s.getvalue()
b'binary data'
>>>

讨论¶

当你想模拟一个普通的文件的时候 StringIO 和 BytesIO 类是很有用的。 比如,在�元测试中,你�以使用 StringIO �创建一个包�测试数�的类文件对象, 这个对象�以被传给�个�数为普通文件对象的函数。

需�注�的是, StringIO 和 BytesIO 实例并没有正确的整数类型的文件�述符。 因此,它们�能在那些需�使用真实的系统级文件如文件,管�或者是套接字的程�中使用。