Bootstrap FreeKB - Python (Scripting) - Change file or directory owner using os.chown
Python (Scripting) - Change file or directory owner using os.chown

Updated:   |  Python (Scripting) articles

os.chown can be used to update the user (uid) and group (gid) of a file or directory. Here is the minimal boilterplate code without error handling.

#!/usr/bin/python3
import os
os.chown(f"/path/to/file", 1001, 2001)

 

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

#!/usr/bin/python3
import os

try:
  # 1001 is uid (user id)
  # 2001 is gid (group id)
  os.chown(f"/path/to/file", 1001, 2001)
except Exception as exception:
  print(f"Got the following exception when attempting to update /path/to/file to be owned by 1001:2001 - {exception}")
else:
  print(f"Successfully updated /path/to/file to be owned by 1001:2001")

 




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 553ae1 in the box below so that we can be sure you are a human.