StringIO
可与c++的string流比较
在内存中读写str
先创建一个StringIO,然后像文件一样写入
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!
getvalue()
方法用于获得写入后的str。
可以看出write
方法是追加的,而不会把原来的str
覆盖
f.write(str)
会返回长度
>>> n=(f.write('haha'))
>>> n
4
要读取StringIO
,可以用一个str
初始化StringIO
,然后,像读文件一样读取:
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
... s = f.readline()
... if s == '':
... break
... print(s.strip())
...
Hello!
Hi!
Goodbye!
getvalue()
与read()
方法的不同
getvalue会一次性给出str的所有值,而read是从当前位置以后读取
- f.seek(0)
可以重置位置到开头,f.seek(x)位置会到第x个字节
- f.tell()
可以告诉你当前指针所在位置
BytesIO
StringIO
操作的只能是str
,如果要操作二进制数据,就需要使用BytesIO
。
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
请注意,写入的不是str
,而是经过UTF-8编码的bytes。
和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'