How to check folder / file permissions with Pathlib

Viewed 4072

Is there a Pathlib equivalent of os.access()?

Without Pathlib the code would look like this:

import os
os.access('my_folder', os.R_OK)  # check if script has read access to folder

However, in my code I'm dealing with Pathlib paths, so I would need to do this (this is just an example):

# Python 3.5+
from pathlib import Path
import os

# get path ~/home/github if on Linux
my_folder_pathlib = Path.home() / "github"
os.access(str(my_folder_pathlib), os.R_OK)

The casting to str() is kinda ugly. I was wondering if there is a pure Pathlib solution for what I'm trying to achieve?

p.s. I'm aware of the principle "easier to ask for forgiveness", however this is part of a bigger framework, and I need to know as soon as possible if the script has the right permissions to a NAS stored folder.

2 Answers

Use the stat() method on a Path object, then lookup the st_mode attribute.

Path().stat().st_mode

Related