What is the Python way for recursively setting file permissions?
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"
for root, dirs, files in os.walk(path):
for momo in dirs:
os.chown(os.path.join(root, momo), 502, 20)
for momo in files:
os.chown(os.path.join(root, momo), 502, 20)
I'm suprised the shutil
module doesn't have a function for this.
As correctly pointed out above, the accepted answer misses top-level files and directories. The other answers use os.walk
then loop through dirnames
and filenames
. However, os.walk
goes through dirnames
anyway, so you can skip looping through dirnames
and just chown
the current directory (dirpath
):
def recursive_chown(path, owner):
for dirpath, dirnames, filenames in os.walk(path):
shutil.chown(dirpath, owner)
for filename in filenames:
shutil.chown(os.path.join(dirpath, filename), owner)