Python3 os.chmod() Method
Python3 OS File/Directory Methods
Overview
The os.chmod() method is used to change the permissions of a file or directory.
Available on Unix systems.
Syntax
chmod()The method syntax is as follows:
os.chmod(path, mode)
Parameters
pathFile name path or directory path.
flagsIt can be generated by bitwise OR 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. Deleting or adding files in a directory requires both write and execute permissions. File permissions are checked in the order of user id -> group id -> others, and 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 and directories in the directory can only be deleted or changed by the owner 0o1000
- stat.S_ISGID:Executing this file makes the process's effective group the file's group 0o2000
- stat.S_ISUID:Executing this file makes the process's effective user the file owner 0o4000
- stat.S_IREAD:Set to read-only on Windows
- stat.S_IWRITE:Remove read-only on Windows
Return Value
This method does not return a value.
Example
The following example demonstrates the use of the chmod() method:
#!/usr/bin/python3
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!!Other Extensions