如何使用Python更改文件的权限?
允许用户对文件执行的操作受其文件权限的约束。更改文件的权限时,会修改文件对读取、写入和执行的权限。
本文将介绍如何在Python中更改文件的权限。
使用 os.chmod() 方法
要修改文件的权限,请使用 os.chmod() 方法。
语法
以下是 os.chmod() 方法的语法:
os.chmod(path, mode)
其中,path 表示文件的路径,mode 包含如下解释的不同值。
此方法没有返回值。
Os.chmod() 模式
以下是 os.chmod() 的不同模式参数:
- stat.S_ISUID − 执行时,设置组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
以下是一个更改文件权限的示例:
import os import sys import stat # Setting the given file to be read by the owner. os.chmod("C:\Users\Lenovo\Downloads\Work TP\trial.py", stat.S_IREAD) print("The file can only be ready by owner") # Setting the given file to be read by group. os.chmod("C:\Users\Lenovo\Downloads\Work TP\trial.py", stat.S_IRGRP ) print("The file access gets changed, now it can be read by group.")
输出
以下是上述代码的输出:
The file can only be ready by owner The file access gets changed, now it can be read by group
示例 - 2
以下是一个更改文件权限的示例:
import os import sys import stat # Setting the given file to be read, write and execute by group. os.chmod("C:\Users\Lenovo\Downloads\Work TP\trial.py", stat.S_IRWXG ) print("The file can be read, write and execute by group" # Setting the given file to be read, write and execute by others. os.chmod("C:\Users\Lenovo\Downloads\Work TP\trial.py", stat.S_IRWXO ) print("The file access gets changed, now it can be read, write and execute by others.")
输出
以下是上述代码的输出:
The file can be read, write and execute by group The file access gets changed, now it can be read, write and execute by others
使用Linux
我们可以使用subprocess.call()函数在Linux中更改文件或目录的权限。Python的subprocess包含一个call()方法,用于启动应用程序。
示例
以下是如何使用subprocess.call()函数更改文件权限的示例:
import subprocess subprocess.call(['chmod', '0444', 'myFile.txt'])
输出
输出将显示文件的权限已更改。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP