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()

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...