Python os.chmod() Method

Python OS File/Directory Methods


Overview

The os.chmod() method is used to change the permissions of a file or directory.

Syntax

chmod()The method syntax is as follows:

os.chmod(path, mode)

Parameters

  • path-- File path or directory path.

  • flags-- Can be generated by bitwise OR operation of the following options. Read permission on a directory means you can obtain the list of file names in the directory. Execute permission means you can switch the working directory to this directory. To delete or add files in a directory, you must have both write and execute permissions. File permissions are checked in the order user id -> group id -> others. The first matching allow or deny permission is applied.

    • stat.S_IXOTH:Other users have execute permission 0o001
  • stat.S_IWOTH:Other users have write permission 0o002
  • stat.S_IROTH:Other users have read permission 0o004
  • stat.S_IRWXO:Other users have all permissions (permission mask) 0o007
  • stat.S_IXGRP:Group users have execute permission 0o010
  • stat.S_IWGRP:Group users have write permission 0o020
  • stat.S_IRGRP:Group users have read permission 0o040
  • stat.S_IRWXG:Group users have all permissions (permission mask) 0o070
  • stat.S_IXUSR:Owner has execute permission 0o100
  • stat.S_IWUSR:Owner has write permission 0o200
  • stat.S_IRUSR:Owner has read permission 0o400
  • stat.S_IRWXU:Owner has all permissions (permission mask) 0o700
  • stat.S_ISVTX:Files/directories in the directory can only be deleted or changed by the owner 0o1000
  • stat.S_ISGID:When executing this file, the effective group of the process is the group of the file 0o2000
  • stat.S_ISUID:When executing this file, the effective user of the process is the owner of the file 0o4000
  • stat.S_IREAD:Set to read-only on Windows
  • stat.S_IWRITE:Cancel read-only on Windows

Return Value

This method has no return value.

Example

The following example demonstrates the use of the chmod() method:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys, stat

# 假定 /tmp/foo.txt 文件存在,设置文件可以通过用户组执行

os.chmod("/tmp/foo.txt", stat.S_IXGRP)

# 设置文件可以被其他用户写入
os.chmod("/tmp/foo.txt", stat.S_IWOTH)

print "修改成功!!"

The output of the above program is:

Modification successful!!

Python OS File/Directory Methods

Other Extensions