如何使用 Python 更改文件的权限?
programmingpythonserver side programming更新于 2025/3/22 18:20:17
允许对文件执行操作的用户受其文件权限的约束。当文件的权限改变时,文件的读取、写入和执行权限也会改变。
本文将介绍如何在 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'])
输出
作为输出,我们将能够看到文件的权限已发生改变。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

