Python os.chmod() 方法



Python os.chmod() 方法將路徑的模式更改為指定的數字模式。模式可以取以下值之一或它們的按位或組合 -

  • stat.S_ISUID - 設定使用者 ID 以執行。

  • stat.S_ISGID - 設定組 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 - 由其他人執行。

語法

以下是Python os.chmod() 方法的語法 -

os.chmod(path, mode);

引數

  • path - 這是要設定模式的路徑。

  • mode - 這可以取上述值之一或它們的按位或組合。

返回值

此方法不返回值。

示例 1

以下示例顯示了 Python os.chmod() 方法的用法。在這裡,我們首先將檔案設定為僅由組執行,方法是將 stat.S_IXGRP 作為模式引數傳遞給該方法。然後,我們將 stat.S_IWOTH 作為模式引數傳遞給該方法。這指定只有其他人才能寫入該檔案。

import os, sys, stat
# Assuming /tmp/foo.txt exists, Set a file execute by the group.
os.chmod("/tmp/foo.txt", stat.S_IXGRP)
# Set a file write by others.
os.chmod("/tmp/foo.txt", stat.S_IWOTH)
print ("Changed mode successfully!!")

當我們執行上述程式時,它會產生以下結果 -

Changed mode successfully!!

示例 2

在這裡,我們首先將檔案設定為僅由組寫入。這是透過將 stat.S_IWGRP 作為模式引數傳遞給該方法來完成的。然後,我們將 stat.S_IXGRP 作為模式引數傳遞給該方法。這指定只有組才能執行該檔案。

# importing the libraries
import os
import sys
import stat
# Setting the given file written by the group.
os.chmod("Code.txt", stat.S_IWGRP)
print("This file can only be written by the group")
# Setting the given file executed by the group.
os.chmod("Code.txt", stat.S_IXGRP)
print("Now the file can only be executed by the group.")

在執行上述程式碼時,我們得到以下輸出 -

This file can only be written by the group
Now the file can only be executed by the group.

示例 3

在這裡,當我們使用 os.chmod() 方法時,我們在設定許可權之前編寫了 0o。它表示八進位制整數。檔案許可權設定為 755,這意味著所有者可以讀取、寫入和搜尋;其他人和組只能在檔案中搜索。

import os
file = "code.txt"
os.chmod(file, 0o755)
stat = os.stat(file)
mode = oct(stat.st_mode)[-4:]
print('The mode is:',mode)

以下是上述程式碼的輸出 -

The mode is: 0666
os_file_methods.htm
廣告