简体   繁体   English

是否有来自 pathlib 的路径 function 可以检查子文件夹?

[英]Has Path from pathlib a function which can check subfolders?

I want to find all python files in a folder which are not located in a subfolder (eg '.ipynb_checkpoints' ).我想在不位于子文件夹(例如'.ipynb_checkpoints' )的文件夹中找到所有 python 文件。

My current solution is我目前的解决方案是

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)
]

which gives me the correct list.这给了我正确的清单。

Neverteheless I was hoping that pathlib has some function like f.includes() or something similar. Neverteheless 我希望pathlib有一些 function 像f.includes()或类似的东西。

Is there a soltion to generate the same list only using the functions of the pathlib package?是否有解决方案仅使用pathlib package 的功能生成相同的列表?

To prune the .ipynb_checkpoints directories from the search, I would use os.walk .要从搜索中.ipynb_checkpoints目录,我会使用os.walk

file_list = []
for root, subdirs, files in os.walk(rootdir.resolve()):
    # Select .py files from the current directory
    file_list.extend(fnmatch.filter(files, '*.py'))

    # In-place removal of checkpoint directories to prune them
    # from the walk.
    subdirs[:] = filter(lambda x: x != ".ipynb_checkpoints", subdirs)

From os.walk :os.walk

When topdown is True , the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames ;topdownTrue时,调用者可以就地修改dirnames列表(可能使用del或 slice 赋值),并且walk()只会递归到名称保留在dirnames中的子目录; this can be used to prune the search,...这可以用来修剪搜索,...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 pathlib 比较路径/检查最近添加的文件 - Compare Path/Check for recently added Files with pathlib 如何从 pathlib.path 获取给定文件所在的文件夹名称? - How to get folder name, in which given file resides, from pathlib.path? 从 pathlib 部分元组到字符串路径 - From pathlib parts tuple to string path pathlib.Path.home() 中的 pathlib 库错误:类型对象 'Path' 没有属性 'home' - pathlib library error in pathlib.Path.home() : type object 'Path' has no attribute 'home' 无法从 Jupyter-lab notebook 和 pathlib.Path 导入位于父文件夹中的模块 - Can't import module situated in parent folder from Jupyter-lab notebook and pathlib.Path 如何使用相同的语法模拟 pathlib.Path.open 和 pathlib.path.unlink? - How can I mock pathlib.Path.open and pathlib.path.unlink with the same syntax? 将另一个后缀添加到已经具有 pathlib 后缀的路径 - Adding another suffix to a path that already has a suffix with pathlib 如何检查两个python pathlib.Path是否具有相同的父项? - How to check that two python pathlib.Path have the same parents? 如何使用pathlib从当前路径的一部分创建一个新的Path对象? - How to make a new Path object from parts of a current path with pathlib? pathlib 模块中的 python 路径不添加路径分隔符 - python Path from pathlib module doesn't add path separator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM