Python os.chmod() - 更改文件或目录的权限

Python os.chmod()

Python中的os.chmod()方法用于更改文件或目录的权限

语法:

os.chmod(path, mode)

参数:

Path -文件或目录路径的路径名称

Mode—Mode可以取以下值之一:

  • stat.S_ISUID:设置执行时的用户ID
  • stat.S_ISGID:在执行时设置组ID
  • stat.S_ENFMT:执行记录锁定
  • stat.S_ISVTX:执行后保存文本图像
  • stat.S_IREAD:由所有者阅读。
  • stat.S_IWRITE:由所有者写入。
  • stat.S_IEXEC:由所有者执行。
  • stat.S_IRWXU:由所有者进行读、写和执行
  • stat.S_IRUSR:由所有者阅读
  • stat.S_IWUSR:所有者写入。
  • stat.S_IXUSR:由所有者执行。
  • stat.S_IRWXG:按组读、写和执行
  • stat.S_IRGRP:按组读
  • stat.S_IWGRP:按组写
  • stat.S_IXGRP:按组执行
  • stat.S_IRWXO:由其他人读取、写入和执行。
  • stat.S_IROTH:其他人读
  • stat.S_IWOTH:别人写
  • stat.S_IXOTH:被其他人执行

示例1

# Python program to explain os.chmod() method
  
# importing necessary libraries
import os, sys, stat
  
# Set given file read by the owner.
os.chmod("/Geeks/gfg.txt", stat.S_IREAD)
print("File can be read only by owner.")
  
# Set given file read by others.
os.chmod("/Geeks/gfg.txt", stat.S_IROTH)
print("File access changed, can be read by others now.")

输出:

File can be read only by owner.
File access changed, can be read by others now.

示例2

# Python program to explain os.chmod() method
  
# importing necessary libraries
import os, sys, stat
  
# Set given file written by the owner.
os.chmod("/Geeks/gfg.txt", stat.S_IWRITE)
  
# Set given file executed by the owner.
os.chmod("/Geeks/gfg.txt", stat.S_IXUSR)
print("File can be written and executed only by owner.")

输出:

File can be written and executed only by owner.

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程