If I'm given a path as a string, such as "~/pythoncode/*.py" what is the best way to glob it in pathlib
?
如果我给一个字符串的路径,例如“〜/ pythoncode / * .py”,在pathlib中将它全局化的最佳方法是什么?
Using pathlib, there is a way of appending to a path using a glob:
使用pathlib,有一种方法可以使用glob追加到路径:
p = pathlib.Path('~/pythoncode/').expanduser().glob('*.py')
but this, for example, does not work because the user isn't expanded:
但是,例如,这不起作用,因为用户未展开:
p = pathlib.Path().glob('~/pythoncode/*.py')
and this is generates an exception because I'm providing no arguments to glob()
:
这会产生一个异常,因为我没有为glob()提供任何参数:
p = pathlib.Path('~/pythoncode/*.py').expanduser().glob()
Is there a way to do this in pathlib
, or must I parse the string first?
有没有办法在pathlib中执行此操作,还是必须先解析字符串?
1 个解决方案
#1
3
If you're starting from the string "~/pythoncode/*.py"
and you'd like to expand and glob, you will need to split the path first. Luckily pathlib provides .name
and .parent
to help you out:
如果您从字符串“〜/ pythoncode / * .py”开始并且想要展开和glob,则需要首先拆分路径。幸运的是,pathlib提供了.name和.parent来帮助你:
path = pathlib.Path("~/pythonpath/*.py")
pathlib.Path(path.parent).expanduser().glob(path.name)
Note this simple solution will only work when only the name
includes a glob, it will not work with globs in other parts of the path, like: ~/python*/*.py
. A more general solution that is slightly more complex:
请注意,这个简单的解决方案仅在名称包含glob时才起作用,它不适用于路径其他部分的globs,例如:〜/ python * / * .py。更通用的解决方案稍微复杂一些:
path = pathlib.Path("~/python*/*.py").expanduser()
parts = path.parts[1:] if path.is_absolute() else path.parts
pathlib.Path(path.root).glob(str(pathlib.Path("").joinpath(*parts)))
#1
3
If you're starting from the string "~/pythoncode/*.py"
and you'd like to expand and glob, you will need to split the path first. Luckily pathlib provides .name
and .parent
to help you out:
如果您从字符串“〜/ pythoncode / * .py”开始并且想要展开和glob,则需要首先拆分路径。幸运的是,pathlib提供了.name和.parent来帮助你:
path = pathlib.Path("~/pythonpath/*.py")
pathlib.Path(path.parent).expanduser().glob(path.name)
Note this simple solution will only work when only the name
includes a glob, it will not work with globs in other parts of the path, like: ~/python*/*.py
. A more general solution that is slightly more complex:
请注意,这个简单的解决方案仅在名称包含glob时才起作用,它不适用于路径其他部分的globs,例如:〜/ python * / * .py。更通用的解决方案稍微复杂一些:
path = pathlib.Path("~/python*/*.py").expanduser()
parts = path.parts[1:] if path.is_absolute() else path.parts
pathlib.Path(path.root).glob(str(pathlib.Path("").joinpath(*parts)))