Change permissions for folder, all subfolders, and all files
Asked Answered
P

2

3

I am trying to call shutil.rmtree(some_folder), but it is causing an error that another process is using some file in the subtree. This is not the case, so I'm assuming permissions are not set correctly.

How can I change the permissions of all subfolders and files under some root to writeable, so I can call shutil.rmtree and get rid of them?

Thanks

Phenology answered 29/7, 2011 at 14:50 Comment(1)
What platform are you on? What is your file system? What is the exact error message?Second
S
9

On a platform with the chmod command available, you could do this:

subprocess.call(['chmod', '-R', '+w', some_folder])

Assuming that some_folder is a string that is the full-path to the folder you want to modify.

Sofia answered 29/7, 2011 at 15:2 Comment(0)
E
7

Using os:

import os
def change_permissions_recursive(path, mode):
    for root, dirs, files in os.walk(path, topdown=False):
        for dir in [os.path.join(root,d) for d in dirs]:
            os.chmod(dir, mode)
        for file in [os.path.join(root, f) for f in files]:
            os.chmod(file, mode)

If you just want to make them writable additional to the flags:

import os, stat
def get_perm(fname):
    return stat.S_IMODE(os.lstat(fname)[stat.ST_MODE])

def make_writeable_recursive(path):
    for root, dirs, files in os.walk(path, topdown=False):
        for dir in [os.path.join(root, d) for d in dirs]:
            os.chmod(dir, get_perm(dir) | os.ST_WRITE)
        for file in [os.path.join(root, f) for f in files]:
            os.chmod(file, get_perm(file) | os.ST_WRITE)

If you are on Windows, this might not work correctly, see the documentation of os.chmod.

Elielia answered 29/7, 2011 at 19:41 Comment(2)
For Py3+ I believe the constants should be stat.S_IWRITE and so forth.Rudderhead
add os.chmod(path, get_perm(path) | os.ST_WRITE)Kelm

© 2022 - 2024 — McMap. All rights reserved.