Handle a missing file

EasyException Handling Programs · 13 of 20

Write a Python program that opens a file and handles the case where it does not exist.

Advertisement
Output
exists.txt -> hello
missing.txt -> not found

Approach

  1. Catch FileNotFoundError.

Solution

Python
for name in ["exists.txt", "missing.txt"]:    if name == "exists.txt":        with open(name, "w") as f:            f.write("hello")    try:        with open(name) as f:            print(name, "->", f.read())    except FileNotFoundError:        print(name, "-> not found")
Output
exists.txt -> hello
missing.txt -> not found

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment