今天第一次进行 文件遍历,自己递归写的时候还调试了好久,(主要因为分隔符号的问题),后来发现了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~

Python 用 os.walk 遍历目录的更多相关文章

  1. python中os.walk()遍历目录中所有文件

    之前一直用判断目录和文件的递归方法来获取一个目录下的所有文件,后来发现python里面已经写好了这个函数,不需要自己递归获取了,记录下os.walk()函数的用法 目的:获取path下所有文件,返回由 ...

  2. python通过os.walk() 遍历出多级目录下所有文件绝对路径

    代码如下 将遍历出来的路径全部添加到列表中: def get_all_abs_path(source_dir): path_list = [] for fpathe, dirs, fs in os.w ...

  3. python中os.walk浏览目录和文件

    #!/usr/bin/env python # 2.py # use UTF-8 # Python 3.3.0 # os.walk()的使用 import os # 枚举dirPath目录下的所有文件 ...

  4. 利用 os.walk() 遍历目录

    os.walk: walk(top, topdown=True, onerror=None, followlinks=False) 参数: top 要遍历的目录地址 topdown 为真,则优先遍历t ...

  5. Python 使用 os 模块遍历目录/获取当前文件的路径

    1.列出指定目录下所包含的目录 item = os.listdir("/Users/jinchengxie/go") 返回的是一个列表, 里面包含了指定目录下所包含的所有的目录 2 ...

  6. os.walk() 遍历目录下的文件夹和文件

    os.walk(top, topdown=True, onerror=None, followlinks=False) top:顶级目录 os.walk()返回一个三元tupple(dirpath, ...

  7. python os.walk()遍历

    os.walk()遍历 import os p='/bin' #设定一个路径 for i in os.walk(p): #返回一个元组 print (i) # i[0]是路径 i[1]是文件夹 i[2 ...

  8. Python:os.walk()和os.path.walk()用法

    转于:https://www.cnblogs.com/zmlctt/p/4222621.html 博主:zmlctt 一.os.walk() 函数声明:os.walk(top,topdown=True ...

  9. Python模块 os.walk

    Os.walk os.walk(top,topdown=True,onerror=None,followlinks=False) os.walk()是python中内置(built-in)的目录树生成 ...

随机推荐

  1. jquerymobile UI使用

    <!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="utf-8& ...

  2. 10位IT领袖给应届毕业生的10条忠告

    10位IT领袖给应届毕业生的10条忠告,在走向独立和自主的伟大征程中,吸取他们的经验. 在毕业生们迈出象牙塔之时,他们应该听从哪些人的建议?在走向独立和自主的伟大征程中,他们该吸取哪些教训?听一听各领 ...

  3. USACO Section 2.3: Zero Sum

    这题我做得比较麻烦,网上有个比较简单的程序. /* ID: yingzho1 LANG: C++ TASK: zerosum */ #include <iostream> #include ...

  4. lib-qqwry v1.0 发布 nodejs解析纯真IP库(qqwry.dat)

    lib-qqwry是当初学习node时用来练手的一个模块,用来解析纯真IP库的 现在发一个v1.0版本弥补我当时稚嫩的代码. 意外收获是,整理代码后发现,相比v0.x版本 急速模式下的效率提升大概20 ...

  5. hdu 4565 So Easy!(矩阵+快速幂)

    题目大意:就是给出a,b,n,m:让你求s(n); 解题思路:因为n很可能很大,所以一步一步的乘肯定会超时,我建议看代码之前,先看一下快速幂和矩阵快速幂,这样看起来就比较容易,这里我直接贴别人的推导, ...

  6. 蓝牙接收苹果手机通知 ANCS协议分析

    蓝牙接收苹果手机通知 ANCS协议分析 转载,请注明出处:http://www.cnblogs.com/alexcai/p/4321514.html 综述 现在有许多蓝牙手表.手环都能接收苹果ipho ...

  7. Android中的sp与wp

    一.相关code文件 二.code具体分析 lightrefebase: refbase: sp: wp: flag: 三.使用注意事项 不能在把目标对象赋给一个长久存在的sp对象之前赋给一个短生命周 ...

  8. 解决 iReport 生成 pdf 时显示不出中文的问题

    有没有遇到这样的情况:在使用 iReport 做报表时,用pdf预览显示不出中文? 解决步骤是这样的: 1.加入jar包 下载两个jar包:itextasian.jar 和 itext-x.y.jar ...

  9. Eclipse 上安装 Maven3插件

    原文:http://www.cnblogs.com/quanyongan/archive/2013/04/18/3028181.html eclipse 安装插件的方式最常见的有两种: 1. 一种是在 ...

  10. BZOJ 3624 免费道路

    第一反应:这不先0后1做并查集就行了吗? 然后WA了... 哦....啊?哦...233 如果按顺序做并查集,有些0的边可能很重要(只能由它作为0连起两个联通块),但并没有被选. 于是先按1做并查集, ...