How do I iterate over a subfolder in Python 1

How do I iterate over a subfolder in Python

import os

def list_files(dir):
    r = []
    for root, dirs, files in os.walk(dir):
        for name in files:
            r.append(os.path.join(root, name))
    return r

Here is what the above code is Doing:
1. os.walk() returns a generator that yields a tuple of 3 values on each iteration:
a. the current directory
b. a list of subdirectories in the current directory
c. a list of files in the current directory
2. The for loop iterates over the files in the current directory
3. os.path.join() joins the current directory with the file name to create a full path
4. The full path is appended to the list

Similar Posts