首页 > 技术文章 > python 字符串的I/O 操作

baxianhua 2018-12-29 17:18 原文

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

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

推荐阅读