python學習——StringIO和BytesIO


StringIO

很多時候,數據讀寫不一定是文件,也可以在內存中讀寫。

StringIO顧名思義就是在內存中讀寫str。

要把str寫入StringIO,我們需要先創建一個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。

要讀取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!

BytesIO

StringIO操作的只能是str,如果要操作二進制數據,就需要使用BytesIO。

BytesIO實現了在內存中讀寫bytes,我們創建一個BytesIO,然后寫入一些bytes:

>>> 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。

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

和StringIO類似,可以用一個bytes初始化BytesIO,然后,像讀文件一樣讀取:

>>> from io import StringIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'

小結

StringIO和BytesIO是在內存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。

轉自https://blog.csdn.net/youzhouliu/article/details/51914536


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM