使用 Python 实现文件递归遍历的三种方式


Posted in Python onJuly 18, 2018

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

先发出来看看:

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):
    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,把文件和文件夹用 if~else~ 进行了分支处理,当然,自我调用的循环还是存在。

有木有更好的方式呢?网上一搜一大把,原来有一个现成的 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 则是先输出顶级文件夹,然后是顶级文件,再输出第二级文件夹,以及第二级文件,以此类推,具体大家可以把上面脚本拷贝后自行验证。

总结

以上所述是小编给大家介绍的使用 Python 实现文件递归遍历的三种方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
在Django同1个页面中的多表单处理详解
Jan 25 Python
python 函数传参之传值还是传引用的分析
Sep 07 Python
Python xlwt设置excel单元格字体及格式
Apr 18 Python
如何实现删除numpy.array中的行或列
May 08 Python
python爬虫之urllib3的使用示例
Jul 09 Python
Python2实现的图片文本识别功能详解
Jul 11 Python
在Python中给Nan值更改为0的方法
Oct 30 Python
python 动态调用函数实例解析
Oct 21 Python
基于Django实现日志记录报错信息
Dec 17 Python
Python使用turtle库绘制小猪佩奇(实例代码)
Jan 16 Python
django 读取图片到页面实例
Mar 27 Python
python PyAUtoGUI库实现自动化控制鼠标键盘
Sep 09 Python
详解flask入门模板引擎
Jul 18 #Python
Sanic框架基于类的视图用法示例
Jul 18 #Python
flask入门之表单的实现
Jul 18 #Python
Flask入门之上传文件到服务器的方法示例
Jul 18 #Python
flask入门之文件上传与邮件发送示例
Jul 18 #Python
Sanic框架流式传输操作示例
Jul 18 #Python
django 发送邮件和缓存的实现代码
Jul 18 #Python
You might like
PHP弹出提示框并跳转到新页面即重定向到新页面
2014/01/24 PHP
PHP实现的sqlite数据库连接类
2014/12/12 PHP
PHP准确取得服务器IP地址的方法
2015/06/02 PHP
php通过baihui网API实现读取word文档并展示
2015/06/22 PHP
jquery为页面增加快捷键示例
2014/01/31 Javascript
Javascript this 关键字 详解
2014/10/22 Javascript
jQuery判断指定id的对象是否存在的方法
2015/05/22 Javascript
基于jquery实现放大镜效果
2015/08/17 Javascript
window.onload使用指南
2015/09/13 Javascript
jQuery中Chosen三级联动功能实例代码
2017/03/07 Javascript
angular directive的简单使用总结
2017/05/24 Javascript
详解react-webpack2-热模块替换[HMR]
2017/08/03 Javascript
ES6中javascript实现函数绑定及类的事件绑定功能详解
2017/11/08 Javascript
Parcel 打包示例(React HelloWorld)
2018/01/16 Javascript
jQuery使用$.extend(true,object1, object2);实现深拷贝对象的方法分析
2019/03/06 jQuery
layui禁用侧边导航栏点击事件的解决方法
2019/09/25 Javascript
[03:06]2018年度CS GO最具人气解说-完美盛典
2018/12/16 DOTA
Python求两个list的差集、交集与并集的方法
2014/11/01 Python
Python创建xml的方法
2015/03/10 Python
火车票抢票python代码公开揭秘!
2018/03/08 Python
用Python实现BP神经网络(附代码)
2019/07/10 Python
python实现电子书翻页小程序
2019/07/23 Python
Django 后台获取文件列表 InMemoryUploadedFile的例子
2019/08/07 Python
python中类的输出或类的实例输出为这种形式的原因
2019/08/12 Python
Tensorflow训练模型越来越慢的2种解决方案
2020/02/07 Python
基于python实现对文件进行切分行
2020/04/26 Python
python如何实现word批量转HTML
2020/09/30 Python
python request 模块详细介绍
2020/11/10 Python
红色连衣裙精品店:Red Dress Boutique
2018/08/11 全球购物
JAVA程序员面试题
2012/10/03 面试题
总经理文秘岗位职责
2014/02/03 职场文书
2014年教研室工作总结
2014/12/06 职场文书
优秀教师申报材料
2014/12/16 职场文书
交警失职检讨书
2015/01/26 职场文书
卫生保健工作总结2015
2015/05/18 职场文书
css让页脚保持在底部位置的四种方案
2022/07/23 HTML / CSS