Fix Python – Python how to write to a binary file?


Asked By – Aaron Hiniker

I have a list of bytes as integers, which is something like

[120, 3, 255, 0, 100]

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

Would this work?

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file

Now we will see solution for issue: Python how to write to a binary file?


This is exactly what bytearray is for:

newFileByteArray = bytearray(newFileBytes)

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, because bytes 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.

Python 3.x:

>>> bytearray(newFileBytes)
>>> bytes(newFileBytes)

Python 2.x:

>>> bytearray(newFileBytes)
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

This question is answered By – abarnert

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0