Chapter 9: Reading and writing files

Opening and reading binary files

face Josiah Wang

Python will open a file in text mode by default.

To open a binary file, you should also supply the "b" (binary) mode (along with the "r" if you are reading the file).

file = open("test.png", "rb")
data = file.read()
print(type(data))  # <class 'bytes'>

In binary mode, Python will read in the content of the file as bytes, which is a Python built-in type. We are not covering bytes in this course, because you are unlikely to have to program to such low-level details for your degree. Any bytes we will discuss in our course will be the ones given by a snake!

And don’t worry, more snake puns will be coming your way during our live classes!! 🐍🐍🐍

In any case, you will largely be using external libraries to handle binary files. For example, you might need to store your machine learning model as a binary file, but you will use a specific library to load and save your model.

If you really want to be geeky, a byte is 8 bits (bit == “binary digit”, i.e. 0 or 1, or a boolean). So 0010 1011 is a byte.

Hopefully you now also know the difference between 50 Megabytes per second (MBps) and 50 Megabits per second (Mbps), so that you don’t get cheated by your Internet provider! 😀