How to prevent pathlib’s Path.glob from returning files when the glob ends in a slash?

和自甴很熟 提交于 2021-02-05 06:02:10

问题


The the new Path.glob from pathlib seems to behave differently from the old glob.glob when the glob pattern ends in a slash it seems.

In [1]: from pathlib import Path

In [2]: from glob import glob

In [3]: glob('webroot/*/')
Out[3]: ['webroot/2017-06-07/']

In [4]: list(Path().glob('webroot/*/'))
Out[4]: 
[PosixPath('webroot/.keep'),
 PosixPath('webroot/2017-06-07'),
 PosixPath('webroot/matches.2017-06-07.json')]

Is that by design, some compatibility issue I haven’t encountered? And is there a way to stop it from doing that?

For now I’ll work around it with:

[path for path in Path().glob('webroot/*/') if path.is_dir()]

回答1:


There's an open bug about this:

  • https://bugs.python.org/issue22276

No resolution yet.

Your workaround looks fine, although if you don't mind also including the 'webroot' directory itself you may prefer using a ** glob:

>>> list(Path('webroot').glob('**'))
[PosixPath('webroot'), PosixPath('webroot/2017-06-07')]


来源:https://stackoverflow.com/questions/44420100/how-to-prevent-pathlib-s-path-glob-from-returning-files-when-the-glob-ends-in-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!