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'