Ignore Directories and Missing Files (Solution)

In this lesson, you’ll explore a solution to the task of making your wordcount command resilient to directories and missing files. You’ll learn how to handle these scenarios gracefully using Python’s exception handling mechanism.

Know Your Starting Point

Here’s the initial state of your program from the previous task:

Python src/wordcount.py
import sys
from pathlib import Path

def main():
    path = Path(sys.argv[1] if len(sys.argv) > 1 else "-")
    if path.name == "-":
        raw_text = sys.stdin.buffer.read()
    else:
        raw_text = path.read_bytes()
    text = raw_text.decode("utf-8")
    num_lines = text.count("\n")
    num_words = len(text.split())
    num_bytes = len(raw_text)
    max_digits = len(str(max(num_lines, num_words, num_bytes)))
    output = (
        f"{num_lines:>{max_digits}} "
        f"{num_words:>{max_digits}} "
        f"{num_bytes:>{max_digits}}"
    )
    if path.name != "-":
        print(output, path)
    else:
        print(output)

Now, you’re going to handle directories and missing files.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Avatar image for davidbonn

davidbonn on June 20, 2025

Something I was thrown by was that for directories your example in the task description did not include the trailing slash but your implementation did.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on June 23, 2025

@davidbonn Ah, good observation. Thanks for bringing that up! The trailing slash on directories is completely optional. It’s just a habit of mine to include it explicitly to distinguish directories from regular files, so whether or not to include the slash is up to personal preference. Appreciate your attention to detail!

Avatar image for Audrey

Audrey on July 7, 2025

There is an error in the “is a directory” solution. The success criteria does not have a trailing /, but the solution code and pytest expects a trailing /. These clearly contradict each other. Please make them consistent.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on July 8, 2025

@Audrey and @davidbonn, thank you both! The task instructions are fixed now.

Become a Member to join the conversation.