程式扎記: [ Python 常見問題 ] Python how to write to a binary file?

標籤

2015年1月14日 星期三

[ Python 常見問題 ] Python how to write to a binary file?

Source From Here 
Question 
I have a list of bytes as integers, which is something like: 
>>> list = [120, 3, 255, 0, 100]

How can I write this list to a file as binary? 

How-To 
This is exactly what bytearray is for: 
>> newFileBytes = [123, 3, 255, 0, 100]
>> newFileByteArray = bytearray(newFileBytes)
>> newFile = open (directoryPath + newFileCounter + ".txt", "wb")
>> newFile.write(newFileByteArray)

If you're using Python 3.x, you can use bytes instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, becausebytes is just an alias for str. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that. 
Under Python 2.x: 
>>> newFileBytes = [123, 3, 255, 0, 100]
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

Under Python 3.x: 
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'


Supplement 
Python 3.1 快速導覽 - 內建函數 bytearray()

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!