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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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

f = StringIO('hello\nworld!')
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip()) #去除\n
#打印結果
hello
world!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

BytesIO

想要操作二進制數據,就需要使用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'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

請注意,寫入的不是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())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8


免責聲明!

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



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