Write Binary File in Python
Create a small binary file from bytes.
BeginnerFile Handling ProgramsExample 11 of 20
write-binary-file.py
Run in browser1# Program to write a small binary file23filename = input("Enter binary filename to write: ")45data = bytes([0, 1, 2, 3, 255])67with open(filename, "wb") as f:8 f.write(data)910print("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.