Skip to main content

How to write binary data to a file in Python

How to write binary data to a file in Python.

Here's a step-by-step tutorial on how to write binary data to a file in Python.

Step 1: Open the file in binary mode

To write binary data to a file, you need to open the file in binary mode. This can be done using the open() function with the mode set to 'wb'. The 'w' signifies that you want to write to the file, and the 'b' signifies that you want to open it in binary mode.

file = open('data.bin', 'wb')

In the above example, we open a file named data.bin in binary mode for writing. You can replace 'data.bin' with the desired file name or path.

Step 2: Prepare the binary data

Before writing binary data to the file, you need to prepare the data that you want to write. Binary data consists of bytes, which can be represented using the bytes or bytearray data types in Python.

Here's an example where we prepare some binary data using the bytes type:

data = bytes([0x48, 0x65, 0x6c, 0x6c, 0x6f])  # Binary representation of 'Hello'

In this example, we create a bytes object containing the binary representation of the string 'Hello'.

Step 3: Write the binary data to the file

Once you have the binary data prepared, you can write it to the file using the write() method of the file object. The write() method takes the binary data as an argument.

file.write(data)

In the above example, we write the binary data to the file using the write() method.

Step 4: Close the file

After you have finished writing the binary data to the file, it is important to close the file using the close() method. This ensures that any buffered data is written to the file and frees up system resources.

file.close()

In the above example, we close the file using the close() method.

Complete example

Here's a complete example that demonstrates all the steps:

file = open('data.bin', 'wb')
data = bytes([0x48, 0x65, 0x6c, 0x6c, 0x6f]) # Binary representation of 'Hello'
file.write(data)
file.close()

In this example, we open the file data.bin in binary mode, prepare the binary data for the string 'Hello', write the data to the file, and finally close the file.

That's it! You now know how to write binary data to a file in Python.