Python StringIO及BytesIO包使用方法解析
更新時間:2020年06月15日 10:05:07 作者:會飛的貓1122
這篇文章主要介紹了Python StringIO及BytesIO包使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
StringIO
它主要是用在內存讀寫str中。
主要用法就是:
from io import StringIO f = StringIO() f.write(‘12345‘) print(f.getvalue()) f.write(‘54321‘) f.write(‘abcde‘) print(f.getvalue()) #打印結果 12345 1234554321abcde
也可以使用str初始化一個StringIO然后像文件一樣讀取。
f = StringIO(‘hello\nworld!‘) while True: s = f.readline() if s == ‘‘: break print(s.strip()) #去除\n #打印結果 hello world!
BytesIO
想要操作二進制數(shù)據(jù),就需要使用BytesIO。
當然包括視頻、圖片等等。
from io import BytesIO f = BytesIO() f.write(‘保存中文‘.encode(‘utf-8‘)) print(f.getvalue()) #打印結果 b‘\xe4\xbf\x9d\xe5\xad\x98\xe4\xb8\xad\xe6\x96\x87‘
請注意,寫入的不是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())
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)在tkinter中使用matplotlib繪制圖形的方法示例
這篇文章主要介紹了Python實現(xiàn)在tkinter中使用matplotlib繪制圖形的方法,結合實例形式分析了Python使用tkinter與matplotlib進行正弦曲線圖形繪制的相關操作技巧,需要的朋友可以參考下2018-01-01