Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to change the owner of a directory using Python?
Changing the owner of a directory or file in Python requires administrative privileges and uses the pwd, grp, and os modules. The pwd module gets user ID from username, grp gets group ID from group name, and os performs the ownership change.
Following are the methods to change the owner of a directory using Python ?
Using os.chown() Method
The os.chown() method changes the owner and group ID of a given path to specified numeric owner ID (UID) and group ID (GID).
Syntax
os.chown(filepath, uid, gid, *, dir_fd=None, follow_symlinks=True)
Parameters
filepath ? The file or directory path whose ownership to change
uid ? Integer representing the new owner ID (-1 to keep unchanged)
gid ? Integer representing the new group ID (-1 to keep unchanged)
dir_fd ? Optional file descriptor for directory operations
follow_symlinks ? If True (default), follows symbolic links; if False, operates on the link itself
Note: The asterisk (*) indicates that subsequent parameters are keyword-only.
Basic Example
Here's how to change both owner and group ID ?
import os
# Create a test directory first
directory_path = "/tmp/test_directory"
os.makedirs(directory_path, exist_ok=True)
# Check current ownership
print("Current owner ID:", os.stat(directory_path).st_uid)
print("Current group ID:", os.stat(directory_path).st_gid)
# Change owner and group (requires sudo privileges)
new_uid = 1500
new_gid = 1500
os.chown(directory_path, new_uid, new_gid)
print("\nOwnership changed successfully!")
# Verify the change
print("New owner ID:", os.stat(directory_path).st_uid)
print("New group ID:", os.stat(directory_path).st_gid)
The output shows the ownership change ?
Current owner ID: 1000 Current group ID: 1000 Ownership changed successfully! New owner ID: 1500 New group ID: 1500
Changing Only One ID
To change only the owner ID while keeping the group ID unchanged ?
import os
directory_path = "/tmp/test_directory"
print("Before change:")
print("Owner ID:", os.stat(directory_path).st_uid)
print("Group ID:", os.stat(directory_path).st_gid)
# Change only owner ID, keep group ID unchanged (-1)
new_uid = 200
unchanged_gid = -1
os.chown(directory_path, new_uid, unchanged_gid)
print("\nAfter changing only owner ID:")
print("Owner ID:", os.stat(directory_path).st_uid)
print("Group ID:", os.stat(directory_path).st_gid)
Before change: Owner ID: 1500 Group ID: 1000 After changing only owner ID: Owner ID: 200 Group ID: 1000
Working with Symbolic Links
The follow_symlinks parameter controls how symbolic links are handled ?
import os
# Create original file and symbolic link
original_file = "/tmp/original.txt"
symlink_file = "/tmp/symlink.txt"
with open(original_file, 'w') as f:
f.write("test content")
os.symlink(original_file, symlink_file)
print("Before changing symlink ownership:")
print("Original file UID:", os.stat(original_file).st_uid)
print("Symlink UID:", os.stat(symlink_file).st_uid)
# Change ownership following symlink (default behavior)
os.chown(symlink_file, 200, 200)
print("\nAfter changing with follow_symlinks=True:")
print("Original file UID:", os.stat(original_file).st_uid)
print("Symlink UID:", os.stat(symlink_file).st_uid)
# Change ownership of symlink itself
os.chown(symlink_file, 400, 400, follow_symlinks=False)
print("\nAfter changing with follow_symlinks=False:")
print("Original file UID:", os.stat(original_file).st_uid)
print("Symlink UID (via lstat):", os.lstat(symlink_file).st_uid)
Using shutil.chown() Method
The shutil.chown() method provides a higher-level interface that accepts usernames and group names instead of numeric IDs.
Syntax
shutil.chown(filepath, user=None, group=None)
Example
Using usernames and group names instead of numeric IDs ?
import shutil
import os
from pathlib import Path
# Create test directory
directory_path = "/tmp/test_dir"
os.makedirs(directory_path, exist_ok=True)
# Get current ownership information
path_info = Path(directory_path)
current_owner = path_info.owner()
current_group = path_info.group()
print("Current owner:", current_owner)
print("Current group:", current_group)
# Change ownership using usernames (requires appropriate user/group to exist)
try:
shutil.chown(directory_path, user="nobody", group="nogroup")
print("\nOwnership changed successfully!")
# Check new ownership
updated_info = Path(directory_path)
print("New owner:", updated_info.owner())
print("New group:", updated_info.group())
except (KeyError, PermissionError) as e:
print(f"Error changing ownership: {e}")
Comparison
| Method | ID Type | Advantages | Use Case |
|---|---|---|---|
os.chown() |
Numeric UID/GID | Direct, precise control | System administration scripts |
shutil.chown() |
Username/Group name | More readable, user-friendly | Application-level ownership changes |
Important Notes
− Changing file ownership typically requires root privileges (use sudo)
− On Windows, ownership concepts differ significantly from Unix-like systems
− Always handle PermissionError exceptions when changing ownership
− Use -1 in os.chown() to keep UID or GID unchanged
Conclusion
Use os.chown() for precise numeric control over file ownership, and shutil.chown() for user-friendly name-based changes. Both methods require appropriate system permissions to execute successfully.
