Search code examples
pythonpython-3.xoperating-systempathlib

Is there a way to check access with pathlib?


I'm using pathlib now, which makes many things easier for me. But I'm still missing the os.access method. Is there a way to work around with 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")

Solution

  • Based on the information out of the links below I created this code:

    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")
    

    May someone knows a better way to solve this issue with pathlib or can teach me a better understanding of the stat method.

    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