Bootstrap FreeKB - Python (Scripting) - Change file or directory permissions using os.chmod
Python (Scripting) - Change file or directory permissions using os.chmod

Updated:   |  Python (Scripting) articles

os.chmod can be used to update the permissions of a file or directory. Here is the minimal boilterplate code without error handling. It's important to use 0o for the leading zero due to how this handles octets.

#!/usr/bin/python3
import os
os.chmod(f"/path/to/file", 0o775)

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import os

try:
  os.chmod(f"/path/to/file", 0o775)
except Exception as exception:
  print(f"Got the following exception when attempting to update /path/to/file to mode -rwxrwxr-x (0775) - {exception}")
else:
  print(f"Successfully updated /path/to/file to mode -rwxrwxr-x (0775)")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 0d4954 in the box below so that we can be sure you are a human.