Skip to content

Nov 20: Prac6 and Search for Files

Learning Objectives

After today's class, you should be able to:

  • Explain the steps for writing a recursive function in Python.
  • Understand concepts of practice quiz

Announcements

  • Project 3: Music Data
    • Part A Unit Testing: Due Wednesday 11/19 15 points (already due)
    • Part B Nested: Due Friday 11/21 50 points
    • Part C Recursion: Due Wednesday 12/03 15 points
    • Part D API Usage: Due Wednesday 12/03 20 points

Practice Quiz 6

  • Two portions to the quiz: written and coding
  • Log in as student
  • Start exam recording
  • Log in to Canvas only
  • Raise your hand when complete with Canvas written portion
  • Open Thonny for coding portion only
  • Submit code through Canvas (will go to Gradescope)
  • Log out when finished

Recursive Functions

How to write a recursive function:

  • Step 1. Base case: how will the recursion stop?
  • Step 2. Current case: what needs to be computed?
  • Step 3. Recursion: how will the arguments change?

Example: find_files

A recursive function that searches the file system

filesys2.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""Example function for searching a file system.
"""

import os
import sys
from pprint import pprint


def find_files(path, pattern):
    """Find all filenames containing the given pattern.

    Args:
        path (str): The starting (current) location.
        pattern (str): Characters in the filename.

    Returns:
        list: paths of files with pattern in the name
    """
    result = []
    if os.path.isfile(path):
        # Base case: regular file
        basename = os.path.basename(path)
        if pattern in basename:
            result.append(path)
    else:
        # Recursive case: folder
        for entry in sorted(os.listdir(path)):
            entry_path = os.path.join(path, entry)
            result += find_files(entry_path, pattern)
    return result


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python filesys2.py path pattern")
    else:
        result = find_files(sys.argv[1], sys.argv[2])
        pprint(result)

Sample output when run with PA1 simp as command-line args:

py ['PA1/__pycache__/simplify.cpython-312.pyc', 'PA1/__pycache__/test_simplify.cpython-312-pytest-8.4.2.pyc', 'PA1/simplify.py', 'PA1/test_simplify.py']

Note

Special characters in file paths:

  • ~ (tilde) means home folder
  • . (dot) means current folder
  • .. (dot dot) means parent folder