`
alanland
  • 浏览: 633171 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Python 用 os.walk 遍历目录

阅读更多

今天第一次进行 文件遍历,自己递归写的时候还调试了好久,(主要因为分隔符号的问题),后来发现了os.walk方法,就忍不住和大家分享下.


先看下代码:



import os

for i in os.walk('c:'+os.sep+'ant'):
    print i[1]



下面是输出:

c:\ant
c:\ant\bin
c:\ant\docs
c:\ant\docs\ant2
c:\ant\docs\antlibs
c:\ant\docs\antlibs\antunit
c:\ant\docs\antlibs\compress
c:\ant\docs\antlibs\dotnet
c:\ant\docs\antlibs\props
c:\ant\docs\antlibs\svn
c:\ant\docs\images
c:\ant\docs\manual
c:\ant\docs\manual\api
c:\ant\docs\manual\api\org
c:\ant\docs\manual\api\org\apache
c:\ant\docs\manual\api\org\apache\tools
c:\ant\docs\manual\api\org\apache\tools\ant
c:\ant\docs\manual\api\org\apache\tools\ant\dispatch
c:\ant\docs\manual\api\org\apache\tools\ant\filters


后面还有很长.

如果不使用这个方法,遍历同样能达到效果.不过使用 os.walk 方便很多了.这个方法返回的是一个三元tupple(dirpath, dirnames, filenames),

其中第一个为起始路径,

第二个为起始路径下的文件夹,

第三个是起始路径下的文件.
dirpath是一个string,代表目录的路径,

dirnames是一个list,包含了dirpath下所有子目录的名字,

filenames是一个list,包含了非目录文件的名字.这些名字不包含路径信息,如果需要得到全路径,需要使用 os.path.join(dirpath, name).



下面是可以看到 os.walk 方法返回的内容.


代码:


import os

for i in os.walk('c:'+os.sep+'ant'):
    print i
   

输出:

('c:\\ant', ['bin', 'docs', 'etc', 'lib', 'Project'], ['fetch.xml', 'get-m2.xml', 'INSTALL', 'KEYS', 'LICENSE', 'NOTICE', 'README', 'WHATSNEW'])
('c:\\ant\\bin', [], ['ant', 'ant.bat', 'ant.cmd', 'antenv.cmd', 'antRun', 'antRun.bat', 'antRun.pl', 'complete-ant-cmd.pl', 'envset.cmd', 'lcp.bat', 'runant.pl', 'runant.py', 'runrc.cmd'])
('c:\\ant\\docs', ['ant2', 'antlibs', 'images', 'manual', 'projects', 'slides', 'webtest'], ['antnews.html', 'ant_in_anger.html', 'ant_task_guidelines.html', 'appendix_e.pdf', 'breadcrumbs.js', 'bugs.html', 'bylaws.html', 'contributors.html', 'external.html', 'faq.html', 'favicon.ico', 'index.html', 'legal.html', 'LICENSE', 'license.html', 'mail.html', 'mission.html', 'nightlies.html', 'page.css', 'problems.html', 'projects.html', 'resources.html', 'svn.html'])
('c:\\ant\\docs\\ant2', [], ['actionlist.html', 'features.html', 'FunctionalRequirements.html', 'original-specification.html', 'requested-features.html', 'requested-features.txt', 'VFS.txt'])
('c:\\ant\\docs\\antlibs', ['antunit', 'compress', 'dotnet', 'props', 'svn'], ['bindownload.cgi', 'bindownload.html', 'charter.html', 'index.html', 'proper.html', 'sandbox.html', 'srcdownload.cgi', 'srcdownload.html'])
('c:\\ant\\docs\\antlibs\\antunit', [], ['index.html'])
('c:\\ant\\docs\\antlibs\\compress', [], ['index.html'])
('c:\\ant\\docs\\antlibs\\dotnet', [], ['index.html'])
('c:\\ant\\docs\\antlibs\\props', [], ['index.html'])

...


当然后面还有很长了.


有了这个函数无论是遍历文件夹,还是遍历文件都很方便.



下面是我是自己用递归实现的遍历文件方法.

代码:

def listdir(leval,path):
    for i in os.listdir(path):
        print('|  '*(leval + 1) + i)
        if os.path.isdir(path+i):
            listdir(leval+1, path+i)

path = 'c:'+os.sep+'ant'

#或者直接 path='C:/ant'
print(path+os.sep)
listdir(0, path+os.sep)


下面是输出:

c:\ant\
|  bin
|  |  ant
|  |  ant.bat
|  |  ant.cmd
|  |  antenv.cmd
|  |  antRun
|  |  antRun.bat
|  |  antRun.pl
|  |  complete-ant-cmd.pl
|  |  envset.cmd
|  |  lcp.bat
|  |  runant.pl
|  |  runant.py
|  |  runrc.cmd
|  docs
|  |  ant2
|  |  antlibs
|  |  antnews.html
|  |  ant_in_anger.html
|  |  ant_task_guidelines.html
|  |  appendix_e.pdf
|  |  breadcrumbs.js
|  |  bugs.html
|  |  bylaws.html
|  |  contributors.html
|  |  external.html
|  |  faq.html
|  |  favicon.ico
|  |  images
|  |  index.html
|  |  legal.html
|  |  LICENSE
|  |  license.html
|  |  mail.html
|  |  manual
|  |  mission.html
|  |  nightlies.html
|  |  page.css
|  |  problems.html
|  |  projects
|  |  projects.html
|  |  resources.html
|  |  slides
|  |  svn.html
|  |  webtest
|  etc
|  |  ant-bootstrap.jar
|  |  changelog.xsl
|  |  checkstyle
|  |  coverage-frames.xsl
|  |  jdepend-frames.xsl
|  |  jdepend.xsl
|  |  junit-frames-xalan1.xsl
|  |  junit-frames.xsl
|  |  junit-noframes.xsl
|  |  log.xsl
|  |  maudit-frames.xsl
|  |  mmetrics-frames.xsl
|  |  tagdiff.xsl
|  fetch.xml
|  get-m2.xml
|  INSTALL
|  KEYS
|  lib
|  |  ant-1.8.0.pom
|  |  ant-1.8.0.pom.md5
|  |  ant-1.8.0.pom.sha1
|  |  ant-1.8.0.pom.sha512

..


如果只想得到文件夹,而不要文件,把要做的事情放到

if os.path.isdir(path+i):

里面就好了,比如: print()


O(∩_∩)O~



3
1
分享到:
评论
2 楼 zlele 2016-10-24  
你好,这个遍历文件的结果是乱序的吗
1 楼 daqing15 2011-10-24  

相关推荐

    python使用os模块的os.walk遍历文件夹示例

    if __name__ == ‘__main__’: try: ”’traval and list all files and all dirs”’ for root, dirs, files in os.walk(‘D:’ + os.sep + ‘Python27’): print ‘——————-directory < ‘ + root + ...

    遍历[目录和文件](功能与python的os.walk一样)_walk函数_

    C++实现python的os模块的walk函数,可绝对路径,相对路径,源代码以及编译好的二进制可执行文件。

    Python利用递归和walk()遍历目录文件的方法示例

    就需要我们循环迭代出所有文件和子文件夹,Python中遍历指定目录下所有的文件和文件夹,包含多级目录,有两种方法,一种是通过递归思想去遍历,另一种是os模块的walk()函数下面话不多说,就来一起看看详细的介绍:...

    Python使用os.listdir()和os.walk()获取文件路径与文件下所有目录的方法

    在python3.6版本中去掉了os.path.walk()函数 os.walk() 函数声明:walk(top,topdown=True,oneerror=None) 1、参数top表示需要遍历的目录树的路径 2、参数农户topdown默认是”True”,表示首先返回根目录树下的文件...

    Python中os模块功能与用法详解

    本文实例讲述了Python中os模块功能与用法。分享给大家供大家参考,具体如下: OS模块 ...遍历目录 os.path.join 连接目录与文件名 os.path.split 分割文件名与目录 os.path.abspath 获取绝对路径

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

    方式一: #!/usr/bin/python # -*- coding: utf-8 -*- import os def gci(filepath): #遍历filepath下所有文件,包括子目录 ...for fpathe,dirs,fs in os.walk('/root'): for f in fs: print(os.path.join(fpathe,f))

    python 获取文件下所有文件或目录os.walk()的实例

    在python3.6版本中去掉了os.path.walk()函数 os.walk() 函数声明:walk(top,topdown=True,oneerror=None) 1、参数top表示需要遍历的目录树的路径 2、参数农户topdown默认是”True”,表示首先返回根目录树下的文件,...

    fileList - 副本.py

    python 文件目录遍历的demo 通过os.walk遍历目录 有如何接收输入参数 sys.argv 的写法。

    Python获取指定文件夹下的文件名的方法

    模块os中的walk()函数可以遍历文件夹下所有的文件。 os.walk(top, topdown=Ture, onerror=None, followlinks=False) 该函数可以得到一个三元tupple(dirpath, dirnames, filenames). 参数含义: dirpath:string,...

    Python遍历目录中的所有文件的方法

    os.walk(PATH), PATH是个文件夹路径,当然可以用.或者../这样啦. 返回的是个三元元组为元素的列表, 每个元素代表了一个文件夹下的内容.第一个就是当前文件夹下内容. 返回的三元元组代表(该工作文件夹, 该文件夹下的...

    python批量实现Word文件转换为PDF文件

    作者总结了三种遍历目录的方法,分别如下。 2.1.调用glob 遍历指定目录下的所有文件和文件夹,不递归遍历,需要手动完成递归遍历功能。 import glob as gb path = gb.glob('d:\\2\\*') for path in path: print ...

    使用 Python 遍历目录树的方法

    主要介绍了使用 Python 遍历目录树的方法,文中给大家提到了Python os.walk() 函数的相关知识,通过实例代码给大家介绍的非常详细,需要的朋友可以参考下

    Python遍历目录的4种方法实例介绍

    主要介绍了Python遍历目录的4种方法实例介绍,本文讲解了使用os.popen运行shell列表命令、利用glob模块、利用os.listdir(推荐)、利用os.walk(推荐)等4种方法,需要的朋友可以参考下

    python 搜索大文件的实例代码

    如下所示: ... for root,dirs,files in os.walk(pathname):#这里os.walk()遍历目录 for file in files: fname = os.path.abspath(os.path.join(root,file)) if os.path.getsize(fname)>filesize:

    faster-than-walk:在Python 3上更快的递归目录遍历

    快于行走 图书馆速度os.walk(std lib) 225.98 fast_than_walk 69.0 在此仓库中,基准从Dockerfile在Docker上运行。 速度是IRL时间,是要完成10000个完整的递归目录移动到/usr/share/ 。 这在很大程度上取决于I / O...

    python遍历一个目录,输出所有的文件名的实例

    python 获取一个文件夹内(包括子文件夹)所有文件的名字和路径 import os dir = "e:\\" for root, dirs, files in os.walk(dir): for file in files: print os.path.join(root,file) 或: import os path = r'e:\...

    python删除过期log文件操作实例解析

    1. 用Python遍历目录 os.walk方法可以很方便的得到目录下的所有文件,会返回一个三元的tupple(dirpath, dirnames, filenames),其中,dirpath是代表目录的路径,dirnames是一个list,包含了dirpath下的所有子目录的...

Global site tag (gtag.js) - Google Analytics