Write Binary File
Create a small binary file from bytes.
BeginnerTopic: File Handling Programs
Python Write Binary File Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to write a small binary file
filename = input("Enter binary filename to write: ")
data = bytes([0, 1, 2, 3, 255])
with open(filename, "wb") as f:
f.write(data)
print("Binary data written to", filename)Output
Enter binary filename to write: sample.bin Binary data written to sample.bin
Understanding Write Binary File
Opening in "wb" mode writes raw bytes; here we create a simple bytes object as a demo.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.