Binary File
In Python, a binary file is a type of computer file that stores data in binary format. This means that the file’s content is intended to be read and interpreted by software, rather than directly by humans. Binary files can contain a wide variety of data, such as images, audio, video, or compiled software code.
When you work with binary files in Python, you typically use the built-in open()
function with the read binary ("rb"
) or write binary ("wb"
) modes to handle the file’s contents appropriately.
Because binary files aren’t intended to be read directly by humans, they can store more complex data structures and are generally more space-efficient than text files.
Example
Here’s an example of how to read from and write to a binary file in Python:
>>> # Writing to a binary file
>>> with open("example.bin", mode="wb") as file:
... data = bytearray([120, 3, 255, 0, 100])
... file.write(data)
...
5
>>> # Reading from a binary file
>>> with open("example.bin", mode="rb") as file:
... data = file.read()
...
>>> list(data)
[120, 3, 255, 0, 100]
In this example, you create a binary file named example.bin
and write a sequence of bytes to it. Note that the .write()
method returns the number of written bytes. Then, you read the file and convert its content back to a list.
Related Resources
Tutorial
Reading and Writing Files in Python (Guide)
In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.
For additional information on related topics, take a look at the following resources:
- Reading and Writing WAV Files in Python (Tutorial)
- Why Is It Important to Close Files in Python? (Tutorial)
- Python's zipfile: Manipulate Your ZIP Files Efficiently (Tutorial)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Reading and Writing WAV Files in Python (Quiz)
- Manipulating ZIP Files With Python (Course)