在python3中,当对未知的(用户输入)文件路径进行操作时,我需要支持./r*/*.dat
之类的通配符。计划使用这样的东西(简化):
paths = []
for test in userinputs:
paths.extend(pathlib.Path().glob(test))
这对于相对路径很有用;但是,当用户提供绝对路径(应该允许他们这样做)时,代码将失败:
NotImplementedError: Non-relative patterns are unsupported
如果它是一个“简单”的glob,例如/usr/bin/*
,我可以执行以下操作:
test = pathlib.Path("/usr/bin/*")
sources.extend(test.parent.glob(test.name))
但是,像我的第一个路径示例一样,我需要在路径的任何部分(例如/usr/b*/*
)中使用通配符。
是否有一个优雅的解决方案?我觉得我缺少明显的东西。
答案 0 :(得分:1)
Path()
采用一个参数作为其起始目录。
为什么不测试输入以查看是否为绝对路径,然后将Path()
用作根目录?像这样:
for test in userinputs:
if test[0] == '/':
paths.extend(pathlib.Path('/').glob(test[1:]))
else:
paths.extend(pathlib.Path().glob(test))
答案 1 :(得分:0)
作为Nullman答案的附录:
pathlib.Path.is_absolute()可能是一个很好的跨平台选项。
通过https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.is_absolute
答案 2 :(得分:0)
是否有不能使用 glob.glob
的原因?
import glob
paths = []
for test in userinputs:
# 'glob' returns strings relative to the glob expression,
# so convert these into the format returned by Path.glob
# (use iglob since the output is just fed to a generator)
extras = (Path(p).absolute() for p in glob.iglob(test))
paths.extend(extras)