Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globbing Absolute Paths With Pathlib

In python3, when operating on unknown (user-input) file paths, I need to support wildcards such as ./r*/*.dat. The plan was to use something like this (simplified):

paths = []
for test in userinputs:
   paths.extend(pathlib.Path().glob(test))

This works great for relative paths; however, when the user provides an absolute path (which they should be allowed to do), the code fails:

NotImplementedError: Non-relative patterns are unsupported

If it's a "simple" glob, like /usr/bin/*, I can do something like:

test = pathlib.Path("/usr/bin/*")
sources.extend(test.parent.glob(test.name))

However, like my first path example, I need to account for wildcards in any of the parts of the path, such as /usr/b*/*.

Is there an elegant solution for this? I feel like I'm missing something obvious.

like image 318
Michael Avatar asked Sep 15 '25 10:09

Michael


1 Answers

Path() takes a parameter for its starting dir.
Why not test the input to see if an absolute path and then init Path() as the root dir? something like:

for test in userinputs:
    if test[0] == '/':
        paths.extend(pathlib.Path('/').glob(test[1:]))
    else:
        paths.extend(pathlib.Path().glob(test))
like image 134
Nullman Avatar answered Sep 18 '25 10:09

Nullman