Write Binary File in Python

Create a small binary file from bytes.

BeginnerFile Handling ProgramsExample 11 of 20
write-binary-file.py
Run in browser
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.