Basic

When the file is missing

Files fail for reasons you cannot predict: missing, locked, full, unreadable. The plan is to handle the failure where you open.

What you will see

start end

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Handle a missing file.

1

Empty default.

data = "" print(len(data))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0
2

Missing path check.

import os print(os.path.exists("nope.txt"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
False
3

Retry count.

tries = 0 while tries < 2: tries += 1 print(tries)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
2
4

Both lines print.

print("start") print("end")

Before you run it, say out loud what it will print. Then open the answer.

What it prints
start end

Data Flow

A missing or locked file raises at the open. Handle it there, name the path in the message, and decide missing on purpose.
1 open the file
↓
2 catch the reason
↓
3 pick a response
↓
4 say what happened
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

data = "" sets nothing on screen
print(len(data)) 0
Why this works
Handle at the open

The open is where the failure happens, so it is where the handling belongs. A wide catch turns a clear error into a mystery.

Decide missing on purpose

A missing input can mean empty, default, or fatal. Pick one and say it in the message, so the choice is visible.

Examples

Catch at the open

try:
    with open("in.txt") as f:
        data = f.read()
except FileNotFoundError:
    data = ""
print(len(data))

Handle the miss next to the open. A wide try around everything hides real bugs.

A default instead of a crash

import os
path = "nope.txt"
data = "" if not os.path.exists(path) else "x"
print(data)

A missing config can mean empty settings. Decide that on purpose, not by luck.

Fail with a message

import sys
print("cannot read the file", file=sys.stderr)

A failure the user never sees is a silent wrong answer. Name the path in the message.

Retry a locked file

import time
tries = 0
while tries < 2:
    tries += 1
print(tries)

Another process can hold the file briefly. Retry a small number of times, then give up.

Permission denied is different

import os
print(os.path.exists("nope.txt"))

Missing and unreadable are different answers. A missing file may be fine, a locked one is not.

Write the failure too

print("start")
print("end")

A tool that stops quietly leaves no trace. Print the path and the reason on the error stream.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Paths and folders
Previous Lesson
Paths and folders
Next Lesson
Reading JSON files
Reading JSON files →