You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用pathlib函数筛选不在指定子文件夹中的Python文件?

使用pathlib原生方法筛选排除指定子文件夹的Python文件

当然可以用pathlib的原生属性完成这个需求,不用把路径转成字符串,这里有两种更可靠的实现方式:

方法一:利用Path.parts检查路径组成

Path.parts会返回路径各个组成部分的元组,直接检查排除文件夹名是否在其中即可:

from pathlib import Path

rootdir = Path('/home/my_path')
exclude_dir = '.ipynb_checkpoints'

file_list = [
    f for f in rootdir.resolve().glob('**/*.py')
    if exclude_dir not in f.parts
]

比如路径/home/my_path/.ipynb_checkpoints/test.py的parts为('/', 'home', 'my_path', '.ipynb_checkpoints', 'test.py'),通过检查元组中是否包含目标文件夹名,就能快速过滤掉位于该子文件夹内的文件。

方法二:利用Path.parents检查父目录

如果担心文件名中包含目标字符串导致误判(比如有文件名叫test.ipynb_checkpoints.py),可以用Path.parents遍历文件的所有父目录,检查是否有名称匹配的文件夹:

from pathlib import Path

rootdir = Path('/home/my_path')
exclude_dir = '.ipynb_checkpoints'

file_list = [
    f for f in rootdir.resolve().glob('**/*.py')
    if not any(parent.name == exclude_dir for parent in f.parents)
]

f.parents会返回文件所有父路径的迭代器,逐一检查这些父目录的名称是否等于排除文件夹名,这种方式只针对文件夹判断,不会误判文件名里的相似字符串。

这两种方法都完全依赖pathlib的原生属性,不需要转换路径为字符串,比你原来的实现更贴合pathlib的设计,也更可靠。

内容的提问来源于stack exchange,提问作者mosc9575

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:21:30