遍历指定路径下的所有文件和目录

from pathlib import Path


def list_path(root: Path) -> None:
    for p in root.iterdir():
        if p.is_dir():
            list_path(p)
        else:
            # 这里可以写对文件做处理的函数

解释一下上面用到的函数

1. iterdir()方法

语法:Pathobject.iterdir()
功能:返回一个生成器, 迭代指定路径这下所有的文件和文件夹
p = Path()
list(p.iterdir())

"""
输出:
[WindowsPath('.idea'), WindowsPath('aa.txt'), WindowsPath('b.json'), WindowsPath('C3.py'),
WindowsPath('d'), WindowsPath('out.log'), WindowsPath('test.py'),
WindowsPath('TestPath.py'), WindowsPath('__pycache__')]
"""

2. is_dir()方法和is_file()方法

  • 语法:Pathobject.is_dir()
    功能:判断给定路径是否是目录
  • 语法:Pathobject.is_file()
    功能:判断给定路径是否是文件
发布了10 篇原创文章 · 获赞 7 · 访问量 380

猜你喜欢

转载自blog.csdn.net/dreaming_coder/article/details/104010279