Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check folder / file permissions with Pathlib

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.

like image 982
NumesSanguis Avatar asked Oct 24 '19 05:10

NumesSanguis


People also ask

Is Pathlib better than OS?

With Pathlib, you can do all the basic file handling tasks that you did before, and there are some other features that don't exist in the OS module. The key difference is that Pathlib is more intuitive and easy to use. All the useful file handling methods belong to the Path objects.

What does Pathlib path do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.


1 Answers

From Python 3.6, os.access() accepts path-like objects, therefore no str() needed anymore: https://docs.python.org/3/library/os.html#os.access

Although this is still not a pure Pathlib solution.

like image 59
NumesSanguis Avatar answered Sep 21 '22 12:09

NumesSanguis