欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python StringIO及BytesIO包使用方法解析

 更新時間:2020年06月15日 10:05:07   作者:會飛的貓1122  
這篇文章主要介紹了Python StringIO及BytesIO包使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

StringIO

它主要是用在內(nèi)存讀寫str中。

主要用法就是:

from io import StringIO

f = StringIO()
f.write(‘12345‘)
print(f.getvalue())

f.write(‘54321‘)
f.write(‘a(chǎn)bcde‘)

print(f.getvalue())

#打印結(jié)果
12345
1234554321abcde

也可以使用str初始化一個StringIO然后像文件一樣讀取。

f = StringIO(‘hello\nworld!‘)
while True:
  s = f.readline()
  if s == ‘‘:
    break
  print(s.strip()) #去除\n
#打印結(jié)果
hello
world!

BytesIO

想要操作二進制數(shù)據(jù),就需要使用BytesIO。

當然包括視頻、圖片等等。

from io import BytesIO

f = BytesIO()
f.write(‘保存中文‘.encode(‘utf-8‘))

print(f.getvalue())
#打印結(jié)果
b‘\xe4\xbf\x9d\xe5\xad\x98\xe4\xb8\xad\xe6\x96\x87‘

請注意,寫入的不是str,而是經(jīng)過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())

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論