How to write binary data to a file using Python?

PythonServer Side ProgrammingProgramming

"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default. To open files in binary mode, when specifying a mode, add 'b' to it.

For example

f = open('my_file', 'w+b')
byte_arr = [120, 3, 255, 0, 100]
binary_format = bytearray(byte_arr)

This opens a file in binary write mode and writes the byte_arr array contents as bytes in the binary file, my_file.

Updated on 13-Dec-2019 10:31:33