有没有一种方法可以检查pathlib的访问权限?

时间:2020-07-04 11:48:40

标签: python python-3.x operating-system pathlib

我现在正在使用pathlib,这对我来说使很多事情变得容易。 但是我仍然缺少os.access方法。有没有办法解决pathlib?

from os import access, R_OK
from pathlib import Path



def check_access(path):
    return access(path, R_OK)

path='path'

if check_access(path):
    print("Path is available")

else:
    print("Path isn't available")

1 个答案:

答案 0 :(得分:0)

根据下面链接中的信息,我创建了以下代码:

from pathlib import Path

def check_access(path, mode=None):
    print(oct(path.stat().st_mode))
    stat = oct(path.stat().st_mode)[2:]
    if len(stat) <= 5:
        stat = f'0{stat}'
        print(stat)
    per_user  = stat[3]
##    per_group = stat[4]
##    per_other = stat[5]


    if mode == 'F_OK':
        return path.exists()
    #is it equally to 040for dir 100 for file?
    if mode == 'R_OK':
        if per_user >='4':
            return True
    if mode == 'W_OK':
        if per_user == 2 or 6 or 7:
            return True
    if mode == 'X_OK':
        if int(stat) % 2:
            return True

path = Path('directory')

if check_access(path, 'W_OK'):
    print("Path is available")

else:
    print("Path isn't available")

也许有人知道使用pathlib解决此问题的更好方法,或者可以教我更好地了解stat方法。

http://permissions-calculator.org/

https://en.wikipedia.org/wiki/File_system_permissions

Better assertEqual() for os.stat(myfile).st_mode

How can I get the Unix permission mask from a file? https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat