如何使用 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'])

输出

作为输出,我们将能够看到文件的权限已更改。

更新于:2022-08-18

20K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.