如何使用 Python 更改目錄的許可權?


在 Python 中,修改目錄的許可權可以使用subprocess模組和chmod()函式(os模組中的函式)。

使用 'subprocess' 模組

Python 中的subprocess模組提供了各種函式來建立新的(子)程序並建立與 I/O 裝置的連線。

此模組有一個名為call()的函式,此函式幫助我們執行底層作業系統的 shell 命令。您只需按推薦順序傳遞相應的命令和所需選項即可。

例如,在 Unix 作業系統中為使用者設定讀寫許可權的命令如下所示:

chmod -R +w <directory_name>

以下是執行此命令的 call() 方法的語法:

subprocess.call(['chmod', '-R', '+w', 'my_folder'])

其中,

  • chmod:使用此命令,您可以修改底層作業系統中檔案/目錄的許可權。
  • -R:這是指示chmod命令遞迴應用許可權更改的標誌。
  • +w mode:這是chmod命令的選項,表示“讀寫”許可權。它為使用者分配對指定目錄的讀寫許可權。

示例

以下是用subprocess模組為目錄設定讀寫許可權的 Python 示例:

import subprocess
subprocess.call(['chmod', '-R', '+w', 'my_folder'])

使用 'os' 模組

我們還可以使用os模組的chmod()函式為目錄設定許可權。以下是語法:

os.chmod(path, mode);

這將接受以下兩個引數:

  • Path:我們要更改其許可權的檔案或目錄的路徑。
  • Mode:所需的許可權以八進位制數表示。

生成路徑

在設定許可權之前,首先我們需要瀏覽所需的目錄,您可以使用os.walk()方法來做到這一點。os.walk()方法的功能與透過自上而下或自下而上遍歷樹生成目錄中的檔名相同,這意味著它從檔案開始,然後向上移動到根目錄。

os.path.join(root, d)函式幫助您連線兩個目錄並建立路徑。

示例

以下是使用chmod()方法為目錄設定許可權的示例,這裡我們正在建立一個遞迴函式,該函式接受路徑和許可權模式作為引數。在此函式中,我們正在:

  • 使用walk()函式生成給定目錄的路徑,在這裡,我們正在將所有目錄從 rot 新增到給定資料夾的路徑中。
  • 使用chmod()方法為所需目錄設定指定的許可權(根據給定的模式引數)。
  • 在呼叫此函式時,我們提供目錄名稱和表示讀寫模式(0o777)的八進位制數作為引數。
import os
#Changing the permissions of all files and directories Recursively
def change_permissions_recursive(path, mode):   
    
   # Traverse the directory tree starting from 'path' to top
   for root, dirs, files in os.walk(path, topdown=False):
	
      # Iterate over the directories in the 'root' directory
      for dir in [os.path.join(root, d) for d in dirs]:
         os.chmod(dir, mode)
        
      # Iterate over the files in the 'root' directory
      for file in [os.path.join(root, f) for f in files]:
         # Change the permissions of each file
         os.chmod(file, mode)

# Calling the function 
change_permissions_recursive('my_folder', 0o777)

更新於: 2024年9月23日

6K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.