Python學習筆記(二十四)StringIO和BytesIO

來源:互聯網
上載者:User

標籤:strip   int   讀寫   獲得   rom   讀檔案   get   byte   imp   

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。

和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‘
小結

StringIO和BytesIO是在記憶體中操作str和bytes的方法,使得和讀寫檔案具有一致的介面。

 

Python學習筆記(二十四)StringIO和BytesIO

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.