Extra Topic: Recursion and Files
Note: extra topics are not in CS Academy, but are required
and can appear on any future
homework, writing session, quiz, or exam.
File System Navigation
Folders can contain folders or files. Since folders can contain other folders,
they are a
recursive data structure. In fact, they are a kind
of recursive structure called a
tree (where each value has exactly one
parent, and there is a topmost or "root" value).
Traversing such a recursive data structure is a natural use of a recursive algorithm!
These programs only run locally (not in the browser), and require
that you first download and expand
sampleFiles.zip
in the same folder as the Python file you are running.
- printFiles
import os
def printFiles(path):
# Base Case: a file. Just print the path name.
if os.path.isfile(path):
print(path)
else:
# Recursive Case: a folder. Iterate through its files and folders.
for filename in os.listdir(path):
printFiles(path + '/' + filename)
printFiles('sampleFiles')
# Note: if you see .DS_Store files in the sampleFiles folders, or in the
# output of your function (as often happens with Macs, in particular),
# don't worry: this is just a metadata file and can be safely ignored.
- listFiles
import os
def listFiles(path):
if os.path.isfile(path):
# Base Case: return a list of just this file
return [ path ]
else:
# Recursive Case: create a list of all the recursive results from
# all the folders and files in this folder
files = [ ]
for filename in os.listdir(path):
files += listFiles(path + '/' + filename)
return files
print(listFiles('sampleFiles'))
- removeTempFiles
Note: Be careful when using os.remove(): it's permanent and cannot be undone!
That said, this can be handy, say to remove .DS_Store files on Macs, and
can be modified to remove other kinds of files, too. Just be careful.
import os
def removeTempFiles(path, suffix='.DS_Store'):
if path.endswith(suffix):
print(f'Removing file: {path}')
os.remove(path)
elif os.path.isdir(path):
for filename in os.listdir(path):
removeTempFiles(path + '/' + filename, suffix)
removeTempFiles('sampleFiles')
# removeTempFiles('sampleFiles', '.txt') # be careful