python os 遍历目录中所有文件-os.walk() 方法
os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
def walk(top, topdown=True, onerror=None, followlinks=False):
参数解释:
- top – 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
- topdown的默认值是“True”,表示首先返回根目录树下的文件,然后遍历目录树下的子目录。值设为False时,则表示先遍历目录树下的子目录,返回子目录下的文件,最后返回根目录下的文件。
topdown设值不同,os.walk()返回的列表元素顺序不同(但不是相反),所以遍历后的结果也不同 - onerror – 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。
- followlinks – 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录。
def get_files_from_dir(dir):
if not os.path.exists(dir):
return ''
file_paths = []
for root, directories, files in os.walk(dir):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
如上,我们只传入一个目录参数,它会遍历当前目录,及其子目录。
返回的是一个三元组(root,dirs,files)
- root 所指的是当前正在遍历的这个文件夹的本身的地址
- dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
- files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
for root, directories, files in os.walk(dir): 每一次循环,返回的就是遍历那个目录下的信息,root为目录路径,dirs为当前遍历的目录中有什么目录,files 为当前遍历的木有中有什么问题。
python遍历文件夹,指定遍历深度与忽略目录的方法
python遍历文件夹,指定遍历深度与忽略目录的方法
参考URL: https://www.jb51.net/article/143620.htm
#!/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)