[英]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 thedirnames
list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain in dirnames ;当topdown为
True
时,调用者可以就地修改dirnames
列表(可能使用del
或 slice 赋值),并且walk()
只会递归到名称保留在dirnames中的子目录; this can be used to prune the search,...这可以用来修剪搜索,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.