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