chmod() function of os module in Python

The chmod() function of os module in Python changes the file permissions for an existing file. The file is specified by the path parameter and the permissions are specified by the mode parameter.

Os Updated 29 Mar 2023 2 min read

Overview

  • For a file specified by the path parameter, the os.chmod() function sets the file permissions as specified by one or more bit masks that are bitwise ORed and sent through the mode parameter. When a file descriptor is available and file permissions need to be changed using the file descriptor the function os.fchmod() can be used.
  • In Unix and Unix like operating systems a file has Read, Write and Execute permissions specified for the owner, group and others.
  • A call to chmod() function changes all the permissions(for owner, group and others) of a file specified by the path parameter. For example, os.chmod(filePath, stat.S_IRWXU) will not only set Read, Write and Execute permissions for the owner of the file but also removes any permission previously set for the group and others.
  • If one has to set new permissions for owner, group and others or any combination of them, the mode parameter has to be sent the right combination of the masks. For example, if the owner to have Read, Write and Execute permissions and the group to have Read permission and the others to have Read permission the mode parameter to be sent a value of stat.S_IRWXU | stat.S_IRGRP| stat.S_IROTH.
  • The umask() function is to remove any file permissions that are not to be provided during the creation of a file or directory by a process. The chmod() function works on files that have been created already for which the permissions need to be modified.

Example

python
# Example Python program that changes the

            # permissions on a file using chmod() function

            # of the os module

            import os

            import stat

# File for which the permissions need to be changed

            filePath = "/ex/test.txt"

# Read, Write and Execute permissions to the user

            # Read permission to the group

            # None to others

            # chmod 740

            permissions = stat.S_IRWXU | stat.S_IRGRP

            os.chmod(filePath, permissions)

Output

Output
mymac:PEX usr1$ ls -l test.txt

            -rwxr-----  1 root  wheel  3 Mar 28 13:09 test.txt