FileNotFoundError · Exercises
Core Python

FileNotFoundError Exercises

4 exercises that build on the Python FileNotFoundError: No such file or directory lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A FileNotFoundError means Python tried to open or access a file or folder path that does not exist, usually because the path is wrong relative to where the program is running. By the end you can read a FileNotFoundError, find the real reason the path failed, and fix it by correcting the path, creating missing folders or handling the error. You will practise: Predict which files are found; Fix the missing export folder; Write read_lines(); Append to a log, creating folders.

0 / 4 completed

FileNotFoundError practice exercises

1. Predict which files are found

Predict the output Easy

Read the code and type exactly what it prints. Names are case-sensitive here. Then press Check to compare.

Read this code
import os

os.makedirs("shelf", exist_ok=True)
with open("shelf/a.txt", "w") as f:
    f.write("hi")

for name in ["a.txt", "A.txt", "a.txt.txt"]:
    try:
        with open("shelf/" + name) as f:
            f.read()
        print(name, "found")
    except FileNotFoundError:
        print(name, "missing")

2. Fix the missing export folder

Fix the bug Easy

This code saves two rows into exports/scores.csv and reads them back into saved, but it raises FileNotFoundError. Fix it so the file is written and saved equals "Asha,90\nBen,75". Keep the shutil.rmtree line, which just resets the demo.

Your code
import os
import shutil

shutil.rmtree("exports", ignore_errors=True)   # start clean

rows = ["Asha,90", "Ben,75"]
with open("exports/scores.csv", "w") as f:
    f.write("\n".join(rows))

with open("exports/scores.csv") as f:
    saved = f.read()
print(saved)

3. Write read_lines()

Write code Medium

Write read_lines(path) that returns the lines of the text file as a list of strings without trailing newlines. If the file does not exist, return an empty list instead of raising. Catch FileNotFoundError only.

Your code
def read_lines(path):
    with open(path) as f:
        return f.read().splitlines()

print(read_lines("nothing_here.txt"))

4. Append to a log, creating folders

Write code Hard

Write append_log(path, message) that adds message plus a newline to the end of the file at path, creating the file and any missing parent folders if needed. Return the number of lines in the file after appending. It must also work for a plain filename with no folder, like "plain.log".

Your code
def append_log(path, message):
    with open(path, "a") as f:
        f.write(message + "\n")

append_log("logs/app/run.log", "start")

Next lessonPython UnboundLocalError

More Python FileNotFoundError: No such file or directory examples · All Python exercises