今天有个脚本需要遍历获取某指定文件夹下面的所有文件,我记得很早前也实现过文件遍历和目录遍历的功能,于是找来看一看,嘿,不看不知道,看了吓一跳,原来之前我竟然用了这么搓的实现。

先发出来看看:

def getallfiles(dir):
"""遍历获取指定文件夹下面所有文件"""
if os.path.isdir(dir):
filelist = os.listdir(dir)
for ret in filelist:
filename = dir + "\\" + ret
if os.path.isfile(filename):
print filename def getalldirfiles(dir, basedir):
"""遍历获取所有子文件夹下面所有文件"""
if os.path.isdir(dir):
muiop[]
sdrtyuiop[]
getallfiles(dir)
dirlist = os.listdir(dir)
for dirret in dirlist:
fullname = dir + "\\" + dirret
if os.path.isdir(fullname):
getalldirfiles(fullname, basedir)

我是用了 2 个函数,并且每个函数都用了一次 listdir,只是一次用来过滤文件,一次用来过滤文件夹,如果只是从功能实现上看,一点问题没有,但是这…太不优雅了吧。

开始着手优化,方案一:

def getallfiles(dir):
"""使用listdir循环遍历"""
if not os.path.isdir(dir):
print dir
return
dirlist = os.listdir(dir)
for dirret in dirlist:
fullname = dir + "\\" + dirret
if os.path.isdir(fullname):
getallfiles(fullname)
else:
print fullname

从上图可以看到,我把两个函数合并成了一个,只调用了一次 listdir,把文件和文件夹用 ifelse 进行了分支处理,当然,自我调用的循环还是存在。

有木有更好的方式呢?网上一搜一大把,原来有一个现成的 os.walk() 函数可以用来处理文件(夹)的遍历,这样优化下就更简单了。

方案二:

def getallfilesofwalk(dir):
"""使用listdir循环遍历"""
if not os.path.isdir(dir):
print dir
return
dirlist = os.walk(dir)
for root, dirs, files in dirlist:
for file in files:
print os.path.join(root, file)

只是从代码实现上看,方案二是最优雅简洁的了,但是再翻看 os.walk() 实现的源码就会发现,其实它内部还是调用的 listdir 完成具体的功能实现,只是它对输出结果做了下额外的处理而已。

附上os.walk()的源码:

from os.path import join, isdir, islink

# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here. try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = listdir(top)
except error, err:
if onerror is not None:
onerror(err)
return dirs, nondirs = [], []
for name in names:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name) if topdown:
yield top, dirs, nondirs
for name in dirs:
path = join(top, name)
if followlinks or not islink(path):
for x in walk(path, topdown, onerror, followlinks):
yield x
if not topdown:
yield top, dirs, nondirs

至于 listdir 和 walk 在输出时的不同点,主要就是listdir 默认是按照文件和文件夹存放的字母顺序进行输出,而 walk 则是先输出顶级文件夹,然后是顶级文件,再输出第二级文件夹,以及第二级文件,以此类推,具体大家可以把上面脚本拷贝后自行验证。

结语:

跟大家推荐一个学习资料分享群:706315665,里面大牛已经为我们整理好了许多的学习资料,有自动化,接口,性能等等的学习资料!人生是一个逆水行舟的过程,不进则退,咱们一起加油吧!

如何优雅的使用 Python 实现文件递归遍历的更多相关文章

  1. python实现文件夹遍历

    python 中os.path模块用于操作文件或文件夹 os.path.exists(path) 判断文件路径是否存在 dir = "c:\windows"if os.path.e ...

  2. Python学习笔记———递归遍历多层目录

    import os #得到当前目录下所有的文件 def getALLDir(path,sp = ""): filesList = os.listdir(path) #处理每一个文件 ...

  3. python实现二叉树递归遍历与非递归遍历

    一.中序遍历 前中后序三种遍历方法对于左右结点的遍历顺序都是一样的(先左后右),唯一不同的就是根节点的出现位置.对于中序遍历来说,根结点的遍历位置在中间. 所以中序遍历的顺序:左中右 1.1 递归实现 ...

  4. Python 搜索文件,文件过滤,pathlib模块

    1,搜索文件,文件过滤 这里使用:pathlib 模块的  Path.glob(pattern)  方法,该方法可以用来过滤目标文件,以迭代器的形式返回搜索结果. pattern: 通配符:" ...

  5. Python递归遍历目录下所有文件

    #自定义函数: import ospath="D:\\Temp_del\\a"def gci (path): """this is a stateme ...

  6. Python之文件处理-递归删除特定文件

    Python之文件处理-递归删除特定文件 #!/usr/bin/env python # -*- coding:utf-8 -*- import os def delete_particular_fi ...

  7. 如何使用python 新建文件夹以及递归创建文件夹

    转载:如何使用python 新建文件夹以及递归创建文件夹 | 酷python (coolpython.net) 1. os.mkdir 使用python创建文件夹,通常使用os.mkdir方法,在使用 ...

  8. 优雅的使用Python之软件管理

    上篇<优雅的使用python之环境管理>http://dwz.cn/wTsOr,如何管理python环境,有了一个干净的python环境之后,就不可避免的安装python软件包(pytho ...

  9. 优雅的使用python之环境管理

    优雅的使用python之环境管理 缘起 情景1:不同python版本的管理 同一电脑上的多个python版本之前的管理,为了突出问题的普遍存在,下面是有人在segmentfault上提的问题. 摘自: ...

随机推荐

  1. docker 安装 zookeeper

    镜像下载hub.docker.com 上有不少 ZK 镜像, 不过为了稳定起见, 我们就使用官方的 ZK 镜像吧.首先执行如下命令: docker pull zookeeper当出现如下结果时, 表示 ...

  2. WebService常用接口链接(很全面,值得一看)

    天气预报Web服务,数据来源于中国气象局Endpoint :http://www.webxml.com.cn/WebServices/WeatherWebService.asmxDisco       ...

  3. VUE 出现Access to XMLHttpRequest at 'http://192.168.88.228/login/Login?phone=19939306484&password=111' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Contr

    报错如上图!!!!    解决办法首先打开 config -> index.js ,粘贴 如下图代码,'https://www.baidu.com'换成要访问的的api域名,注意只要域名就够了, ...

  4. ThreadLocal是否会导致内存泄露

    什么是内存泄露? 维基百科的定义:[内存泄漏指由于疏忽或错误造成程序未能释放已经不再使用的内存],我的理解就是程序失去了对某段内存的控制,那么这段内存就算是泄露了. ThreadLocal为什么会导致 ...

  5. java中int和integer

  6. R语言之Apriori算法

    ---恢复内容开始--- 1.概念 关联分析:用于发现隐藏在大型数据集中的有意义的联系 项集:0或多个项的集合.例如:{啤酒,尿布,牛奶,花生} 是一个4-项集,意义想象成爸爸去超市买啤酒和花生,给儿 ...

  7. jenkins:一键回滚站点集群

    最近在学习jenkins过程中整理了大量资料,都收录在<jenkins自动化工具使用教程>,但依然缺少一些具体实现细节. 这篇文章,介绍jenkins做集群回滚时的两个设计方案,让一键回滚 ...

  8. FFmpeg命令行工具学习(三):媒体文件转换工具ffmpeg

    一.简述 ffmpeg是一个非常强大的工具,它可以转换任何格式的媒体文件,并且还可以用自己的AudioFilter以及VideoFilter进行处理和编辑.有了它,我们就可以对媒体文件做很多我们想做的 ...

  9. [Swift]LeetCode150. 逆波兰表达式求值 | Evaluate Reverse Polish Notation

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  10. 隔壁老主精讲web页面性能优化。

    首先说一下为什么要进行web页面性能优化,在同样的网络环境下,两个同样能满足你的需求的网站,一个“Biu”的一下就加载出来了,一个卡--卡--卡--卡--卡--才出来,你会选择哪个?研究表明:用户最满 ...