Python| os.access() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统,属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
os.access()
方法使用真实的 uid/gid 来测试对路径的访问。大多数操作使用有效的 uid/gid,因此,该例程可以在 suid/sgid 环境中使用,以测试调用用户是否具有指定的路径访问权限。
句法:
os.access(path, mode)
参数:
path: path to be tested for access or existence
mode: Should be F_OK to test the existence of path, or can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions.
以下值可以作为 access() 的模式参数传递以测试以下内容:
返回:如果允许访问,则返回 True,否则返回 False。
代码 #1:了解 access() 方法
# Python program tyring to access
# file with different mode parameter
# importing all necessary libraries
import os
import sys
# Different mode parameters will
# return True if access is allowed,
# else returns False.
# Assuming only read operation is allowed on file
# Checking access with os.F_OK
path1 = os.access("gfg.txt", os.F_OK)
print("Exists the path:", path1)
# Checking access with os.R_OK
path2 = os.access("gfg.txt", os.R_OK)
print("Access to read the file:", path2)
# Checking access with os.W_OK
path3 = os.access("gfg.txt", os.W_OK)
print("Access to write the file:", path3)
# Checking access with os.X_OK
path4 = os.access("gfg.txt", os.X_OK)
print("Check if path can be executed:", path4)
输出:
Exists the path: True
Access to read the file: True
Access to write the file: False
Check if path can be executed: False
代码 #2:允许验证访问后打开文件的代码
# Python program to open a file
# after validating the access
# checking readability of the path
if os.access("gfg.txt", os.R_OK):
# open txt file as file
with open("gfg.txt") as file:
return file.read()
# in case can't access the file
return "Facing some issue"
输出:
Facing some issue