iterate over folders in directory python code example

Example 1: python iterate directory

import os

directory = r'C:\Users\admin'
for filename in os.listdir(directory):
    if filename.endswith(".jpg") or filename.endswith(".png"):
        print(os.path.join(directory, filename))
    else:
        continue

Example 2: python loop through files in directory recursively

import os
rootdir = './path/to/files/'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

Example 3: python loop through all folders and subfolders

directory = "c:\\folder\\you\\want\\to\\work_on"

for root, subdirectories, files in os.walk(directory):
    for subdirectory in subdirectories:
        print(os.path.join(root, subdirectory))
    for file in files:
        print(os.path.join(root, file))