In the below example we show how to read a binary file in Python.
In this example, we will take a look at how to write to a binary file.
Again we will make use of the build-in open() function, and make use of the flags that will help up write a binary file from the below table.
Character | Meaning |
---|---|
r | open for reading (default) |
w | open for writing, truncating the file first |
x | open for exclusive creation, failing if the file already exists |
a | open for writing, appending to the end of the file if it exists |
b | binary mode |
t | text mode (default) |
+ | open for updating (reading and writing) |
We will have to make use of the w and b characters to write in binary mode.
Example:
First let's create a binary string that we want to write to the binary file.
binary_data = b'Some data to write'
Now let's write it to a file.
with open('data_20230706.bin', 'wb') as binary_file:
binary_file.write(binary_data)
Facing issues? Have Questions? Post them here! I am happy to answer!
- Python List of Lists with Examples
- Fix: ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No matching distribution found for tkinter
- How to Convert Python Notebook .ipynb (JSON) to Executable .py Module
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python: Pandas Merge Indicator (Left, Right and Both) Example
- Fix: EOFError Exception in Python
- How to URL Decode a Query String in Python
- How to take user input from the console in a Python program
- Compare two lists in Python and return matches
- How to change the Python Default version
- Fix: KeyError: exception in Python
- How to get the Execution Time of A Python Program
- Fix: ModuleNotFoundError: No module named boto3 [Python]
- How to get unique values from a list in Python
- How to pip install Python Modules in VSCode
- Python: Fix - TypeError: NoneType object is not iterable
- How to delete a file using Python code example
- How to create a dictionary comprehension in Python
- Python: Get just the filename without extension using Path
- How to comment out a block of code in Python
- How to add two float numbers in Python
- Python: How to POST Json Data with HTTP Request
- Get MD5 Hash as Checksum of a String in Python
- Python - Convert float to String
- How to Parse XML String in Python
- Java 8 Format Date and Time Examples - Java
- How to install Google Chrome on macOS using Terminal Command - Chrome
- JavaScript date in yyyy-MM-dd format - JavaScript
- How to switch from bash to zsh shell in macOS Terminal - MacOS
- Fix: Jupyter Notebook: The port 8888 is already in use, trying another port. - Python
- GitPython: How to check out a Branch - Python
- Use Google Chrome Canvas to create drawings - Chrome
- How to create a Git Project in Eclipse (Step-by-step) - Eclipse