python遍历文件夹,指定遍历深度与忽略目录的方法

yipeiwu_com7年前Python基础

背景

需要在文件夹中搜索某一文件,找到后返回此文件所在目录。用最常规的os.listdir()方式实现了一版,但执行时报错:递归超过最大深度。于是自己添加了点功能,之所有写此函数是为了让它适应不同的项目,因为有项目要找的文件在第一层,有的在第二层。

函数

功能:在文件夹中查找某一文件,找到后返回True与文件所在目录路径。

参数:filepath, 要查找的目录

参数:filename, 要查找的文件

扩展1:find_depth, 查找时指定递归深度;

扩展2:ignore_path, 查找时忽略某些目录;

#!/usr/bin/env python
# coding=utf-8
import os
# from fabric.colors import *

def find_file(self, filepath, filename, find_depth=1, ignore_path=['.git', 'node_modules']):
  """查找文件"""
  # print blue("当前查找目录:{},递归层级:{}".format(filepath, find_depth))
  # 递归深度控制
  find_depth -= 1
  for file_ in os.listdir(filepath):
    # print cyan("file: {}".format(file_))
    if isfile(join(filepath, file_)):
      # print "当前文件:{}".format(file_)
      if file_ == filename:
        return True, filepath
    elif find_depth <= 0: # 递归深度控制, 为0时退出
      # print yellow("超出递归深度,忽略!")
      continue
    elif file_ in ignore_path: # 忽略指定目录
      # print yellow("此目录在忽略列表中,跳过!")
      continue
    else:
      result, abs_path = self.find_file(filepath=join(filepath, file_),
                       filename=filename,
                       find_depth=find_depth)
      if result:
        print green("找到{}文件,所在路径{}".format(filename, abs_path))
        return result, abs_path
  return False, filepath

result, filepath = find_build(filepath="/data/deploy/jenkins/data/jobs/sit-zjims-mobile/workspace/", filename="gulpfile.js", find_depth=3)

以上这篇python遍历文件夹,指定遍历深度与忽略目录的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python针对mysql数据库的连接、查询、更新、删除操作示例

本文实例讲述了python针对mysql数据库的连接、查询、更新、删除操作。分享给大家供大家参考,具体如下: 连接 一 代码 import pymysql # 打开数据库连接 db...

python shell根据ip获取主机名代码示例

这篇文章里我们主要分享了python中shell 根据 ip 获取 hostname 或根据 hostname 获取 ip的代码,具体介绍如下。 笔者有时候需要根据hostname获取i...

python 实现提取log文件中的关键句子,并进行统计分析

利用python开发了一个提取sim.log 中的各个关键步骤中的时间并进行统计的程序: #!/usr/bin/python2.6 import re,datetime file_n...

Python实现通过继承覆盖方法示例

本文实例讲述了Python实现通过继承覆盖方法。分享给大家供大家参考,具体如下: Python真是太动态了,所有的方法默认都是虚的。子类定义父类同名函数之后,父类函数被覆盖。 cla...

Python中asyncio与aiohttp入门教程

Python中asyncio与aiohttp入门教程

很多朋友对异步编程都处于“听说很强大”的认知状态。鲜有在生产项目中使用它。而使用它的同学,则大多数都停留在知道如何使用 Tornado、Twisted、Gevent 这类异步框架上,出现...