Files, Errors and Modules · Working at Scale · lesson 8 of 8
Reading and writing files
about 15 minutes · free · runs in your browser
Step 1 of 2
open, read, close — without the close
open() gives you a file object. Used with with, Python closes it for you even if
something raises:
with open("notes.txt", "w") as f:
f.write("first line\n")
with open("notes.txt") as f:
content = f.read()
The mode is the second argument: "r" read (the default), "w" write — which
truncates the file to nothing first — and "a" append.
Three ways to read:
f.read()— the whole thing as one stringf.readlines()— a list of lines, newlines includedfor line in f:— one line at a time, which is the only option that works on a file bigger than memory
line.rstrip("\n") is the usual way to drop the trailing newline.
In PyLearn these files live in Pyodide's in-memory filesystem, so nothing touches your real disk.
Your turn: write "alpha", "beta" and "gamma" to words.txt, one per
line, then read them back into lines with no trailing newlines.
You start from this, and edit it in the browser:
# Write the three words to words.txt, then read them back into lines.
Step 2 of 2
Processing a file
The everyday shape: read the file, ignore the blank lines, do something with the rest.
Your turn: write count_lines(path) returning how many non-blank lines a file
contains. A line of nothing but spaces counts as blank. Return 0 if the file does not
exist.
You start from this, and edit it in the browser:
def count_lines(path):
# Count the non-blank lines, or return 0 if the file is missing.
pass