Python os.access()方法

Pythonos.access() 方法是使用依赖操作系统的功能的一种有效方法。该方法使用uid/gid (用户标识符/组标识符)来测试对一个路径/文件夹的访问。

os.access() 方法的语法

os.access(path, mode)

参数

path 它是一个文件系统路径或符号链接的地址对象。path 用于存在性、有效性或存在模式。
mode mode 告诉我们要检查path 的哪些特征。
为了测试一个路径的存在,我们使用os.F_OK
要测试一个路径的可读性,我们使用os.R_OK
要测试路径是否可写,我们使用模式os.W_OK
最后一种模式是os.X_OK ,用来确定路径是否可以被执行。

返回

这个方法的返回类型是一个布尔值。如果允许访问,它返回布尔值true ;否则,返回false

例1:在Python中使用os.access() 方法

import os
directory1 = os.access("file.txt", os.F_OK)
print("Does the path exist? :", directory1)
directory2 = os.access("file.txt", os.R_OK)
print("Access to read the file granted :", directory2)
directory3 = os.access("file.txt", os.W_OK)
print("Access to write the file granted :", directory3)
directory4 = os.access("file.txt", os.X_OK)
print("Is the path executable?:", directory4)

输出:

Does the path exist? : False
Access to read the file granted : False
Access to write the file granted : False
Is the path executable?: False

os.access() 在某些操作系统上可能不工作。你可以尝试在代码的开头写上 ,以便根据你的系统要求包含必要的库。import sys

例2:使用Python中的os.access() 方法的条件语句

使用os.access() 方法,在一个文件可用之前,检查用户是否被授权打开该文件。

import os
if os.access("file.txt", os.R_OK):
    with open("file.txt") as file:
        a = file.read()
        print(a)
else:
    print("An error has occurred.")

输出:

An error has occurred.

例3:在Python中使用os.access() 方法后写进文件

import os
file_name = "file.txt"
if os.access(file_name, os.X_OK):
    f1 = open(file_name, 'w')
    f1.write('somethingn')
    f1.close()
else:
    print ("You don't have read permission.")

输出:

You don't have read permission.

I/O 文件操作可能会失败,即使os.access() 返回true ,因为一些网络文件系统的权限语义可能超出通常的 POSIX 权限位模型。