How do you write data into a binary file in python?

Convenient function to write array of int to a file,

def write_array(fname,ray):
    '''
    fname is a file pathname
    ray is an array of int
    '''
    print("write:",fname)
    EncodeInit()
    buffer = [ encode(z) for z in ray ]
    some = bytearray(buffer)
    immutable = bytes(some)
    with open(fname,"wb") as bfh:
        wc = bfh.write(immutable)
        print("wrote:",wrote)
    return wc

How to call the function,

write_array("data/filename",[1,2,3,4,5,6,7,8])

And wrap the following in a class for readable encode/decode:

Encode = {}
Decode = {}
def EncodeInit():
    '''
    Encode[] 0:62 as 0-9A-Za-z
    Decode[] 0-9A-Za-z as 0:62
    '''
    for ix in range( 0,10): Encode[ix] = ix+ord('0')
    for ix in range(10,36): Encode[ix] = (ix-10)+ord('A')
    for ix in range(36,62): Encode[ix] = (ix-36)+ord('a')
    for ix in range( 0,10): Decode[ix+ord('0')] = ix
    for ix in range(10,36): Decode[(ix-10)+ord('A')] = ix
    for ix in range(36,62): Decode[(ix-36)+ord('a')] = ix

def encode(x):
    '''
    Encode[] 0:62 as 0-9A-Za-z
    Otherwise '.'
    '''
    if x in Encode: return Encode[x]
    # else: error
    return ord('.')

def decode(x):
    '''
    Decode[] 0-9A-Za-z as 0:62
    Otherwise -1
    '''
    if x in Decode: return Decode[x]
    # else: error
    return -1

Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:

  1. Open file
  2. Perform operation
  3. Close file

There are four basic modes in which a file can be opened― read, write, append, and exclusive creations. In addition, Python allows you to specify two modes in which a file can be handled― binary and text. Binary mode is used for handling all kinds of non-text data like image files and executable files.

Write Bytes to File in Python

Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file. 

Python3

some_bytes = b'\xC3\xA9'

with open("my_file.txt", "wb") as binary_file:

    binary_file.write(some_bytes)

Output:

my_file.txt

Example 2: This method requires you to perform error handling yourself, that is, ensure that the file is always closed, even if there is an error during writing. So, using the “with” statementis better in this regard as it will automatically close the file when the block ends.

Python3

some_bytes = b'\x21'

binary_file = open("my_file.txt", "wb")

binary_file.write(some_bytes)

binary_file.close()

Output:

How do you write data into a binary file in python?

my_file.txt

Example 3: Also, some_bytes can be in the form of bytearray which is mutable, or bytes object which is immutable as shown below.

Python3

byte_arr = [65,66,67,68]

some_bytes = bytearray(byte_arr)

some_bytes.append(33)

immutable_bytes = bytes(some_bytes)

with open("my_file.txt", "wb") as binary_file:

    binary_file.write(immutable_bytes)

Output:

my_file.txt

Example 4: Using the BytesIO module to write bytes to File

Python3

from io import BytesIO

write_byte = BytesIO(b"\xc3\x80")

with open("test.bin", "wb") as f:

    f.write(write_byte.getbuffer())

Output:

How do you write data into a binary file in python?

test.bin


How do you write data in binary format in Python?

Write Bytes to File in Python Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.

How do you add data to a binary file in Python?

Append data in Binary File.
Open the file in append mode using “ab” Ex.: f = open (“file. dat”,”ab”).
Declare list object to store data which is going to be appended..
Enter data to append..
Append entered data into the declared list object..
Use pickle. dump() method to write the list data..
Close the file..

How do you write data in a binary file?

fwrite( fileID , A ) writes the elements of array A as 8-bit unsigned integers to a binary file in column order. The binary file is indicated by the file identifier, fileID . Use fopen to open the file and obtain the fileID value. When you finish writing, close the file by calling fclose(fileID) .

Which function is used to write data in binary file in Python?

dump(): The method used for writing data to binary file is dump() method.