Write Binary File in Python

Create a small binary file from bytes.

BeginnerFile Handling ProgramsExample 11 of 20
write-binary-file.py
1# Program to write a small binary file
2
3filename = input("Enter binary filename to write: ")
4
5data = bytes([0, 1, 2, 3, 255])
6
7with open(filename, "wb") as f:
8 f.write(data)
9
10print("Binary data written to", filename)

Output

Enter binary filename to write: sample.bin
Binary data written to sample.bin

What's going on

Opening in "wb" mode writes raw bytes; here we create a simple bytes object as a demo.

After this program

If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.