How to Write Binary File in Python: Simple Guide
To write a binary file in Python, open the file with
open('filename', 'wb') mode and use the write() method to save bytes data. This mode ensures data is written exactly as bytes without encoding.Syntax
Use open(filename, 'wb') to open a file for writing in binary mode. The write() method writes bytes data to the file. Always close the file or use with to handle it automatically.
filename: Name of the file to write.'wb': Write mode in binary.write(bytes_data): Writes bytes to the file.
python
with open('example.bin', 'wb') as file: file.write(b'Hello binary world')
Example
This example writes a sequence of bytes to a binary file named data.bin. It demonstrates opening the file in binary write mode and writing bytes data.
python
data = bytes([120, 3, 255, 0, 100]) with open('data.bin', 'wb') as f: f.write(data) print('Binary file written successfully.')
Output
Binary file written successfully.
Common Pitfalls
Common mistakes include:
- Opening the file in text mode ('w') instead of binary mode ('wb'), which causes errors or data corruption.
- Trying to write strings directly without converting to bytes.
- Not closing the file, risking incomplete writes.
Always use with to manage file closing automatically.
python
wrong = "Hello" # Wrong: writing string in binary mode without encoding with open('wrong.bin', 'wb') as f: # f.write(wrong) # This causes TypeError f.write(wrong.encode('utf-8')) # Correct way: encode string to bytes # Correct way: with open('correct.bin', 'wb') as f: f.write(b'Hello')
Quick Reference
Summary tips for writing binary files in Python:
- Use
'wb'mode to write binary files. - Write only bytes objects, not strings.
- Use
withstatement to handle files safely. - Convert strings to bytes with
encode()before writing.
Key Takeaways
Open files with 'wb' mode to write binary data safely.
Write bytes objects, not plain strings, to binary files.
Use the with statement to automatically close files after writing.
Convert strings to bytes using encode() before writing if needed.
Avoid mixing text and binary modes to prevent errors.