The dirs and files lists are all always relative to root – i.e., they are the basename() of the files/folders, i.e. they don’t have a / in them (or \ on windows). You need to join the dirs/files to root to get their whole path if you want your code to work to infinite levels of recursion:
import os
path = "/tmp/foo"
# Change permissions for the top-level folder
os.chmod(path, 502, 20)
for root, dirs, files in os.walk(path):
# set perms on sub-directories
for momo in dirs:
os.chown(os.path.join(root, momo), 502, 20)
# set perms on files
for momo in files:
os.chown(os.path.join(root, momo), 502, 20)
Surprisingly, the shutil module doesn’t have a function for this.