Write Bytes to a File in Python

Write Bytes to a File in Python

Manav Narula Feb-07, 2021 Jan-25, 2021 Python Python File
  1. Write Bytes to a File in Python
  2. Write a Byte Array to a File in Python
  3. Write BytesIO Objects to a Binary File

In this tutorial, we will introduce how to write bytes to a binary file in Python.

Binary files contain strings of type bytes. When we read a binary file, an object of type bytes is returned. In Python, bytes are represented using hexadecimal digits. They are prefixed with the b character, which indicates that they are bytes.

Write Bytes to a File in Python

To write bytes to a file, we will first create a file object using the open() function and provide the file’s path. The file should be opened in the wb mode, which specifies the write mode in binary files. The following code shows how we can write bytes to a file.

data = b'\xC3\xA9'

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

We can also use the append mode - a when we need to add more data at the end of the existing file. For example:

data = b'\xC3\xA9'

with open("test.bin", "ab") as f:
    f.write(data)

To write bytes at a specific position, we can use the seek() function that specifies the file pointer’s position to read and write data. For example:

data = b'\xC3\xA9'

with open("test.bin", "wb") as f:
    f.seek(2)
    f.write(data)

Write a Byte Array to a File in Python

We can create a byte array using the bytearray() function. It returns a mutable bytearray object. We can also convert it to bytes to make it immutable. In the following example, we write a byte array to a file.

arr = bytearray([1,2,5])
b_arr = bytes(arr)

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

Write BytesIO Objects to a Binary File

The io module allows us to extend input-output functions and classes related to file handling. It is used to store bytes and data in chunks of the memory buffer and also allows us to work with the Unicode data. The getbuffer() method of the BytesIO class is used here to fetch a read-write view of the object. See the following code.

from io import BytesIO

bytesio_o = BytesIO(b"\xC3\xA9")

with open("test.bin", "wb") as f:
    f.write(bytesio_o.getbuffer())
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python File

  • Get All the Files of a Directory
  • Delete a File and Directory in Python
  • Append Text to a File in Python
  • Check if a File Exists in Python
  • Find Files With a Certain Extension Only in Python
  • Read Specific Lines From a File in Python