How to change the permission of a directory using Python?

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

>>> import subprocess
>>>['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.

Updated on: 03-Oct-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started