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

yipeiwu_com6年前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设计】。

相关文章

使用pip发布Python程序的方法步骤

使用pip发布Python程序的方法步骤

写过 Python 程序的小伙伴们都知道,需要 import 个非 Python 自带的软件包时,都要用到 pip 这个程序。平时我们都是用 pip,如果我们写好了一个程序,想让大家都能...

Django中间件实现拦截器的方法

Django中间件实现拦截器的方法

1.前言 JavaWeb Struts2的拦截器我们都能很熟悉,在请求交给Action处理之前,先在拦截器中处理,处理完之后再交给Action。 在Django中如何实现相同的效果...

解决pycharm最左侧Tool Buttons显示不全的问题

解决pycharm最左侧Tool Buttons显示不全的问题

问题描述如下: 解决方案如下: 下图中字体调整为18及以上 效果如下: 以上这篇解决pycharm最左侧Tool Buttons显示不全的问题就是小编分享给大家的全部内容了,希望能...

python获取豆瓣电影简介代码分享

复制代码 代码如下:#!/usr/bin/env python#coding:utf-8import re,sysimport urllibfrom bs4 import Beautif...

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...