Path from pathlib有一个可以检查子文件夹的函数吗



我想在一个文件夹中查找所有不在子文件夹中的python文件(例如'.ipynb_checkpoints'(。

我目前的解决方案是

from pathlib import Path
rootdir = Path('/home/my_path')
# For absolute paths instead of relative the current dir
file_list = [
f for f in rootdir.resolve().glob('**/*.py')
if not '.ipynb_checkpoints' in str(f)
]

这给了我正确的列表。

尽管如此,我还是希望pathlib有一些像f.includes()或类似的功能。

是否存在仅使用pathlib包的功能生成相同列表的解决方案?

要从搜索中删除.ipynb_checkpoints目录,我将使用os.walk

import os
import fnmatch
from pathlib import Path
file_list = []
for root, subdirs, files in os.walk(rootdir.resolve()):
# Select .py files from the current directory and create Path
file_list.extend([Path(root, file) for file in fnmatch.filter(files, '*.py')])
# In-place removal of checkpoint directories to prune them
# from the walk.
subdirs[:] = filter(lambda x: x != ".ipynb_checkpoints", subdirs)

来自os.walk:

topdownTrue时,调用方可以在适当的位置修改dirnames列表(可能使用del或切片分配(,并且walk()将只递归到其名称保留在dirnames中的子目录中;这可以用来修剪搜索,。。。

最新更新