发布于 2015-08-30 08:03:03 | 165 次阅读 | 评论: 0 | 来源: 网络整理

问题

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


解决方案

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

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

>>> # Wrap a file interface around an existing string
>>> s = io.StringIO('HellonWorldn')
>>> s.read(4)
'Hell'
>>> s.read()
'onWorldn'
>>>

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

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

讨论

当你想模拟一个普通的文件的时候 StringIOBytesIO 类是很有用的。 比如,在单元测试中,你可以使用 StringIO 来创建一个包含测试数据的类文件对象, 这个对象可以被传给某个参数为普通文件对象的函数。

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

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务