How to change the permission of a directory using Python?

PythonServer Side ProgrammingProgramming

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

>>> import subprocess
>>> subprocess.call(['chmod', '-R', '+w', 'my_folder'])

If you want to use the os module, you'll have to recursively write it:

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)
change_permissions_recursive('my_folder', 0o777)

 This will change the permissions of my_folder, all its files and subfolders to 0o777.

raja
Published on 26-Dec-2017 06:03:49
Advertisements