To open a local file in Python we call the built-in open()
function. This takes a number of arguments, but the most commonly used are:
- file: the path to the file. This is required.
- mode: read, write, append and binary or text. This is optional, but we recommend always specifying it for clarity. Explicit is better than implicit.
- encoding: If the file contains encoded text data, which encoding to use. It's often a good idea to specify this. If you don't specify it, Python will choose a default encoding for you.
At the filesytem level, of course, files contain only a series of bytes. Python, however, distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. When you open a file in binary mode, you are instructing Python to use the data in the file without any decoding; binary mode file reflects the raw data in the file.
A file opened in text mode, on the other hand, treats its contents as if it contains text strings...