如何使用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年8月18日

20K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.