Python os.access() 方法



Python os.access() 方法使用真實的 uid/gid 來測試對路徑/資料夾的訪問許可權。Linux 為系統上的每個使用者分配一個 UID(使用者識別符號)來識別他們可以訪問哪些系統資源。GID(組識別符號)用於在 Linux 中定義組。

此例程可用於 suid/sgid 環境中,以測試呼叫使用者是否對路徑具有給定的訪問許可權,因為大多數操作將使用有效的 uid/gid。如果允許訪問,則返回 True,否則返回 False。

語法

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

os.access(path, mode);

引數

  • path - 這是要測試是否存在或任何訪問許可權的路徑。

  • mode - 應為 F_OK 以測試路徑的存在,或者可以是 R_OK、W_OK 和 X_OK 中的一個或多個的包含或運算,以測試許可權。

    • os.F_OK - 傳遞給 access() 的 mode 引數的值,以測試路徑的存在。
    • os.R_OK - 包含在 access() 的 mode 引數中的值,以測試路徑的可讀性。
    • os.W_OK - 包含在 access() 的 mode 引數中的值,以測試路徑的可寫性。
    • os.X_OK - 包含在 access() 的 mode 引數中的值,以確定路徑是否可以執行。

返回值

如果允許訪問,此方法返回 True,否則返回 False。

示例 1

以下示例顯示了 Python os.access() 方法的用法。在這裡,我們將 檔案的不同路徑及其模式作為引數傳遞給方法。

import os, sys
# Assuming /tmp/foo.txt exists and has read/write permissions.
ret = os.access("/tmp/foo.txt", os.F_OK)
print ("F_OK - return value %s"% ret)
ret = os.access("/tmp/foo.txt", os.R_OK)
print ("R_OK - return value %s"% ret)
ret = os.access("/tmp/foo.txt", os.W_OK)
print ("W_OK - return value %s"% ret)
ret = os.access("/tmp/foo.txt", os.X_OK)
print ("X_OK - return value %s"% ret)

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

F_OK - return value True
R_OK - return value True
W_OK - return value True
X_OK - return value False

示例 2

在下面給出的示例中,os.access() 方法用於檢查使用者是否有權寫入檔案。這裡我們首先使用 open() 函式開啟檔案。然後我們使用 write() 函式寫入它。之後我們 關閉檔案

import os
# checking writability of the path
if os.access("code.txt", os.W_OK):
   with open("code.txt") as f:
      f = open('code.txt', 'w')
      words = "Welcome to tutorialspoint"
      x = f.write(words)
      f.close()
      print('Total characters written including spaces are:',x)
else:
   print("Something went wrong.")

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

Total characters written including spaces are: 25

示例 3

在這裡,os.access() 方法用於在驗證訪問許可權後,確定使用者是否被授權開啟檔案。

import os
# checking the readability of the path
if os.access("code.txt", os.R_OK):
	# opening the txt file as f
	with open("code.txt") as f:
		print (f.read())
else:
    # in case the file cannot be accessed
    print ("Something went wrong.")

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

Welcome to tutorialspoint
os_file_methods.htm
廣告