Python os.fchmod() 方法



Python os.fchmod() 方法將檔案的模式更改為指定的數字模式。模式可以採用以下值之一或它們的按位 OR 組合:

  • 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 2.6 及更高版本中可用。並且僅在 UNIX/LINUX 平臺上可用。

語法

以下是 Python os.fchmod() 方法的語法:

os.fchmod(fd, mode);

引數

  • fd - 這是要設定模式的檔案描述符。

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

返回值

此方法不返回值。

示例 1

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

import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
# Set a file execute by the group.
os.fchmod( fd, stat.S_IXGRP)
# Set a file write by others.
os.fchmod(fd, stat.S_IWOTH)
print ("Changed mode successfully!!")
# Close opened file.
os.close(fd)

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

Changed mode successfully!!

示例 2

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

# importing the libraries
import os
import sys
import stat
# Now open a file "code.txt"
filedesc = os.open("code.txt", os.O_RDONLY )
# Setting the given file written by the group.
os.fchmod(filedesc, stat.S_IWGRP)
print("This file can only be written by the group")
# Setting the given file executed by the group.
os.fchmod(filedesc, 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.fchmod()方法時,我們在設定許可權之前寫了0o。它表示一個八進位制整數。檔案許可權設定為755,這意味著所有者可以讀取、寫入和搜尋;其他使用者和組只能在檔案中搜索。

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

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

The mode is: 0755
python_file_methods.htm
廣告

© . All rights reserved.