總目錄:http://m.itdecent.cn/p/e406a9bc93a9
Python - 子目錄:http://m.itdecent.cn/p/50b432cb9460
如果我們希望有一些信息,不存在磁盤中,在內(nèi)存中就將它完成,最后再存到磁盤內(nèi)。
我們就需要StringIO和BytesIO了。
StringIO
我們來看一個(gè)實(shí)例
from ioimport StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
hello world!
f1 = StringIO('Hello!\nHi!\nGoodbye!')
print(f1.getvalue())
Hello!?
Hi!
Goodbye!?
方法很簡單,我們只需要先創(chuàng)建一個(gè)StringIO,之后就可以寫入一下信息,最后使用getvalue()就可以獲取到內(nèi)部的信息。
我們可以在創(chuàng)建時(shí)直接寫入,也可以先創(chuàng)建好后一步一步寫。
BytesIO
StringIO操作的只能是str,如果要操作二進(jìn)制數(shù)據(jù),就需要使用BytesIO。
其他地方和StringIO差不多。
from ioimport BytesIO
f1 = BytesIO()
f1.write('中文'.encode('utf-8'))
print(f1.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
f2 = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f2.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'