簡體   English   中英

Python字符串包含字節數組

[英]Python string contains byte array

我已經嘗試了一些名為array的Python模塊。 它有一種將數組編碼為字符串的方法。

>>>from array import array
>>>a=[1,2,3]
>>>a=array('B',a)
>>>print(a)
array('B',[1,2,3])
>>>print(a.tostring())
b'\x01\x02\x03'
>>>str(a.tostring())
"b'\x01\x02\x03'"

我想將數組的.tostring()版本保存到文件中,但是open().write()僅接受字符串。

有沒有辦法將此字符串解碼為字節數組?

我想將其用於OpenGL數組( glBufferData接受字節數組)

提前致謝。

無需進一步編碼/解碼數組。 您可以使用'wb'模式將tostring()返回的字節寫入文件:

from array import array
a = array('B', [1, 2, 3])
with open(path, 'wb') as byte_file:
    byte_file.write(a.tostring())

您還可以使用'rb'模式從文件讀取字節:

with open(path, 'rb') as byte_file:
    a = array('B', byte_file.readline())

這將從文件中加載存儲的數組,並將其保存到變量a

>>> print(a)
array('B', [1, 2, 3])

做這個:

>>> open('foo.txt','wb').write(a.tostring())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM