Logo

Developer learning path

Python

Reading and Writing Binary Files in Python

Reading and Writing Binary Files

61

#description

When we talk about reading and writing binary files in Python, we refer to the way in which the data is stored in the file. Binary files contain data that is encoded in binary code - a series of 0s and 1s that represent bits of information.

To read binary files in Python, we can use the open() function with the mode set to "rb" (read binary). This will return a file object that we can read from using methods such as read(), readline(), or readlines().

For example, to read a binary file called "example.bin":

                    
with open("example.bin", "rb") as f:
    data = f.read()
                  

To write binary files in Python, we can use the open() function with the mode set to "wb" (write binary). This will return a file object that we can write to using methods such as write(), writelines(), or seek().

For example, to write binary data to a file called "output.bin":

                    
with open("output.bin", "wb") as f:
    f.write(b"\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64")
                  

In the above example, we are writing the ASCII values for "Hello World" to the file in binary format. Note that the b before the string indicates that it is a bytes object.

It is important to note that binary files can be system-dependent, so make sure to specify the correct encoding and endianness when reading or writing data. Endianness refers to the order in which bytes are stored in memory - little-endian means that the least significant byte is stored first, while big-endian means that the most significant byte is stored first.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.