File handling#

Having discussed all pre-requisites, from encoding to interacting with the file system and juggling paths, we can finally move on to reading and writing files.

open#

The following snippet shows how to use open() to read the contents of a file. It’s best practice to use a with context to automatically close the file handle when done.

with open("file.txt") as f:
    content = f.read()

Instead of slurping the whole file contents at once, you can also iterate over the individual lines, for instance to directly convert them to floats.

contents = []
with open("file.txt") as f:
    for line in f:
        contents.append(float(line))

Mode#

As a second argument, one can provide the mode in which the file should be opened.

Mode

Description

"r"

read-only mode (default)

"w"

write mode, overwriting existing files

"a"

append mode, write by adding to the end of file

"x"

exclusive mode, write mode that fails if the file already exists

"+"

update mode, open to read and write

"rb"

binary read mode to read bytes objects instead of str

"wb"

binary write mode

The following writes a string to a file.

with open("file.txt", "w") as f:
    f.write("lorem ipsum\n")

Encoding#

The optional encoding= and errors= arguments define the encoding to use and how to handle encoding/decoding errors (as already mentioned when discussing encoding in general).

with open("file.txt", encoding="latin1", errors="replace") as f:
    lines = f.readlines()

open with pathlib#

When making use of pathlib, there are multiple equivalent notations to read files.

from pathlib import Path

some_path = Path("file.txt")

with open(some_path) as f:
    content = f.read()

with some_path.open() as f:
    content = f.read()

content = some_path.read_text()

Similarly there are Path.read_bytes(), Path.write_text() and Path.write_bytes() shorthands.