Python 3 – os.chmod() Method
In Python, the os module provides a way to change file or directory permissions using the os.chmod() method.
The os.chmod() method allows the user to modify file or directory permissions in the form of a 3-digit octal number. Each digit represents a specific set of permissions.
- The first digit represents the user’s permissions.
- The second digit represents the group’s permissions.
- The third digit represents the other’s (everyone else) permissions.
There are three possible permissions available to each digit: read (4), write (2), and execute (1). Combining these numbers produces the 3-digit octal number needed for the os.chmod() method.
For example, to set a file’s permissions to read and write for the user, but only read for the group and other users, the 3-digit octal number would be 644 (user: 6, group: 4, other: 4).
Here is an example of how to use the os.chmod() method:
import os
# set file permissions to read and write for the user
os.chmod('/path/to/file', 0o600)
In the above example, the file located at “/path/to/file” has its permissions set to read and write for the file’s user only.
Notice that the second argument passed into os.chmod() is an octal number. The “0o” at the beginning tells Python that the number is in octal format.
Here is a list of common 3-digit octal numbers used for setting file or directory permissions:
- 755 (user: 7, group: 5, other: 5) – allows user to read, write, and execute; allows group and other users to read and execute
- 644 (user: 6, group: 4, other: 4) – allows user to read and write; allows group and other users to read only
- 700 (user: 7, group: 0, other: 0) – allows user to read, write, and execute; does not allow group or other users to access the file or directory
- 777 (user: 7, group: 7, other: 7) – allows everyone full access to read, write, and execute the file or directory
Conclusion
The os.chmod() method is a convenient way to modify file or directory permissions in Python. By using a 3-digit octal number, users can easily control the level of access different users have to their files and directories.