Python os.access()
Python中的 os.access()方法使用真实的uid/gid来测试对path的访问权限。大多数操作使用有效的uid/gid,因此,可以在suid/sgid环境中使用此例程来测试调用用户是否具有指定的路径访问权。
语法:
os.access(path, mode)
参数:
path:要测试访问或存在模式的路径
mode:应该是F_OK来测试路径的存在性,或者可以是一个或多个R_OK、W_OK和X_OK的包含OR来测试权限。
下面的值可以作为access()的模式参数传递来测试以下内容:
- os.F_OK:测试路径是否存在。
- os.R_OK:测试路径的可读性。
- os.W_OK:测试路径可写性。
- os.X_OK:检查路径是否可以执行。
返回:
如果允许访问返回True,否则返回False。
示例1
理解access()方法
# Python program trying 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