Python StringIO及BytesIO包使用方法解析
StringIO
它主要是用在內存讀寫str中。
主要用法就是:
from io import StringIOf = StringIO()f.write(‘12345‘)print(f.getvalue())f.write(‘54321‘)f.write(‘abcde‘)print(f.getvalue())#打印結果123451234554321abcde
也可以使用str初始化一個StringIO然后像文件一樣讀取。
f = StringIO(‘hellonworld!‘)while True: s = f.readline() if s == ‘‘: break print(s.strip()) #去除n#打印結果helloworld!
BytesIO
想要操作二進制數據,就需要使用BytesIO。
當然包括視頻、圖片等等。
from io import BytesIOf = BytesIO()f.write(‘保存中文‘.encode(‘utf-8‘))print(f.getvalue())#打印結果b‘xe4xbfx9dxe5xadx98xe4xb8xadxe6x96x87‘
請注意,寫入的不是str,而是經過UTF-8編碼的bytes。
存放圖片
f = BytesIO()image_open = open(‘./1.jpg‘, ‘rb‘)f.write(image_open.read())image_save = open(‘./2.jpg‘, ‘wb‘)image_save.write(f.getvalue())
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
