【Python】—— 遍历目录下的文件

 

更新日志:

  • [2019-08-21]
    • 修改 yield from list_paths(tmp_path, depth - 1, suffix) 中参数位置的错误
  • [2019-07-17]
    • 添加 v 2.0 版,修复 v 1.0 版本的 depth_count += 1 引起的 bug
    • v 2.0 版本 添加只显示指定后缀的文件的功能
    • 修改文章名称为《【Python】—— 遍历目录下的文件》
    • 删除旧版的表格式描述信息,添加 更新日志 和 说明
  • [2018-09-19]
    • v 1.0 版本发布

说明:


版本 v 2.0

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# File:    : get_paths.py
# @Date    : 2019-07-17 16:19:38
# @Author  : MaiXiaochai
# Email    : maixiaochai@outlook.com
# GitHub   : https://github.com/MaiXiaochai
# @GitPage : https://maixiaochai.github.io

from os import listdir
from os.path import isdir, splitext


def list_paths(dir_path, depth=0, suffix=None):
    """
    1) Generator。
    2) 遍历 dir_path 目录下 所有后缀为 suffix 的文件的路径。
    3) 注意:这里的路径使用'/'。
    :param dir_path:    str     要遍历的目录路径
    :param depth:       int     扫描的深度 0:当前目录,1:当前目录的下一级目录
    :param suffix:      str     文件后缀,如 ".py" 或者 "py"
    :return:            str     文件路径
    """

    # 设定当前目录的表示值
    current_dir_level = 0

    dir_path = dir_path if dir_path.endswith("/") else dir_path + "/"
    suffix = suffix if suffix.startswith('.') else '.' + suffix

    for _path in listdir(dir_path):
        tmp_path = dir_path + _path

        if isdir(tmp_path):
            if current_dir_level < depth:
                yield from list_paths(tmp_path, depth - 1, suffix)

        elif splitext(tmp_path)[-1] == suffix:
            yield tmp_path


def demo():
    test_path = './'
    depth = 1       # 当前目录和下一级目录
    suffix = "py"   # 搜索后缀为"py"的文件
    res = list_paths(test_path, depth, suffix)
    for i in res:
        print(i)


if __name__ == "__main__":
    demo()

版本 v 1.0 

# -*- coding: utf-8 -*-

import os


def get_paths(dir_path, depth=None):
    """
    生成器。
    遍历指定目录下的所有非目录文件, 不会列出目录路径。
    注意:这里的路径使用'/'。
    :param dir_path: str/要遍历的目录路径
    :param depth: int/扫描的深度 0:当前目录,1:当前目录的下一级目录
    :return: str/文件路径, 若当前深度下未发现文件,则不返回。
    """
    depth_count = 0

    depth = int(depth) if depth else 0
    dir_path = dir_path if dir_path.endswith('/') else dir_path + '/'

    for path in os.listdir(dir_path):
        tmp_path = dir_path + path

        if os.path.isdir(tmp_path):
            if depth_count < depth:
                depth_count += 1
                yield from get_paths(tmp_path + '/', depth - 1)

        else:
            yield tmp_path


if __name__ == "__main__":
    the_path = './'
    for i in get_paths(the_path, 2):
        print(i)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值