typestar

Reading and writing files in Python

File IO with with: open, use, and auto-close.

with open("notes.txt", "w") as f:
    f.write("first line\n")
    f.write("second line\n")

with open("notes.txt") as f:
    contents = f.read()

with open("notes.txt") as f:
    lines = [line.rstrip() for line in f]

with open("notes.txt", "a") as f:
    f.write("appended\n")

How it works

  1. Mode "w" writes fresh; "a" appends.
  2. read slurps everything; iterating yields lines.
  3. The with block closes the file even on errors.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
257
Tokens
95
Three-star pace
100 tpm

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

Type this snippet

Step 6 of 7 in Iterators, errors & files, step 49 of 72 in Language basics.

← Previous Next →

Reading and writing files in other languages