typestar

File modes in Python

Read, write, append, exclusive and binary — and what each one destroys.

from pathlib import Path

path = Path("modes.txt")
path.write_text("first\n", encoding="utf-8")

with open(path, "a", encoding="utf-8") as f:
    f.write("second\n")

with open(path, encoding="utf-8") as f:
    print(f.read().splitlines())

with open(path, "rb") as f:
    print(f.read()[:6])

try:
    open(path, "x")
except FileExistsError:
    print("x refuses to clobber")

How it works

  1. w truncates; a appends; x refuses if the file exists.
  2. b gives bytes instead of text, with no newline translation.
  3. encoding should be explicit whenever text crosses machines.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
356
Tokens
123
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 3 of 3 in Errors in depth, step 64 of 72 in Language basics.

← Previous Next →