Python 如何更改文件权限

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'])

输出

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程