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:
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.
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.