python常用库的使用

文件夹遍历以及过滤功能

2019-07-30  本文已影响0人  Freedom2048

遍历文件夹及其子目录

import os
def _iter_files(root_dir):
    # 遍历文件夹及其子目录,返回文件绝对路径
    for root_dir, dirs, file_names in os.walk(root_dir):
        for _dir in dirs:
            _iter_files(_dir)

        for file_name in file_names:
            yield os.path.join(root, file_name)

遍历文件夹及其子目录并支持过滤指定的文件夹和文件扩展名

import os


def _iter_files(src_dir, exclude_file_type, exclude_dir):
    # 遍历文件夹及其子目录,返回文件绝对路径
    for root_dir, dirs, file_names in os.walk(src_dir):
        for _dir in dirs:
            _iter_files(_dir, exclude_file_type, exclude_dir)
        dirs[:] = [dir for dir in dirs if dir not in exclude_dir]
        for filename in file_names:
            file_name, file_ext = os.path.splitext(filename)
            if file_ext in exclude_file_type:
                continue
            yield os.path.join(root_dir, filename)
上一篇 下一篇

猜你喜欢

热点阅读