转自 http://alanland.iteye.com/blog/612459

via @alanland

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

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

  2. Python os.walk() 遍历出当前目录下的文件夹和文件

    os.walk目录遍历 os.walk的参数如下: os.walk(top, topdown=True, onerror=None, followlinks=False) 其中: - top是要遍历的 ...

  3. Python OS导入一个文件夹所有文件

    import os path = 'F:/save_file/seminarseries/' for root, dirs, files in os.walk(path): print(root) 这 ...

  4. Python os.walk文件遍历用法【转】

    python中os.walk是一个简单易用的文件.目录遍历器,可以帮助我们高效的处理文件.目录方面的事情. 1.载入 要使用os.walk,首先要载入该函数 可以使用以下两种方法 import os ...

  5. Python os.walk文件遍历

    os.walk(top, topdown=True, onerror=None, followlinks=False) 可以得到一个三元tupple(dirpath, dirnames, filena ...

  6. python笔记4-遍历文件夹目录os.walk()

    前言 如何遍历查找出某个文件夹内所有的子文件呢?并且找出某个后缀的所有文件 walk功能简介 1.os.walk() 方法用于通过在目录树种游走输出在目录中的文件名,向上或者向下. 2.walk()方 ...

  7. python 遍历文件夹 文件

    python 遍历文件夹 文件   import os import os.path rootdir = "d:\data" # 指明被遍历的文件夹 for parent,dirn ...

  8. python遍历文件夹下的文件

    在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename ...

  9. Python 用 os.walk 遍历目录

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

随机推荐

  1. javascript面向对象知识

    <html> <head> <script></script> </head> <body> <!-- <scrip ...

  2. 生成式对抗网络(GAN)学习笔记

    图像识别和自然语言处理是目前应用极为广泛的AI技术,这些技术不管是速度还是准确度都已经达到了相当的高度,具体应用例如智能手机的人脸解锁.内置的语音助手.这些技术的实现和发展都离不开神经网络,可是传统的 ...

  3. BZOJ1688|二进制枚举子集| 状态压缩DP

    Disease Manangement 疾病管理 Description Alas! A set of D (1 <= D <= 15) diseases (numbered 1..D) ...

  4. Python 获取类对象的父类

    参考 Get parent class name? Python 获取类对象的父类 给定一个类的对象a,要求获取该对象的父类. 方法: a.__class__.__bases__ 返回由该对象的父类组 ...

  5. 运行python “没有那个文件或目录3” 或 “/usr/local/bin/python3^M: bad interpreter: 没有那个文件或目录” 错误

    原因 如果使用的是#!/usr/local/bin/python3这种方式,就会出现 “/usr/local/bin/python3^M: bad interpreter: 没有那个文件或目录” 错误 ...

  6. Error: EACCES: permission denied, mkdir '......node-sass/build'错误解决方案

    安装node-sass时出现一下错误: gyp ERR! configure error gyp ERR! stack Error: EACCES: permission denied, mkdir ...

  7. poj1151 Atlantis (线段树+扫描线+离散化)

    有点难,扫描线易懂,离散化然后线段树处理有点不太好理解. 因为这里是一个区间,所有在线段树中更新时,必须是一个长度大于1的区间才是有效的,比如[l,l]这是一根线段,而不是区间了. AC代码 #inc ...

  8. virtual box centos7 common operation

    ======= network part =======1.设置桥接模式 2.vi /etc/sysconfig/network-scripts/ifcfg-enp0s3BOOTPROTO=stati ...

  9. Kafka知识总结

    1.kafka是什么 类JMS消息队列,结合JMS中的两种模式,可以有多个消费者主动拉取数据,在JMS中只有点对点模式才有消费者主动拉取数据. kafka是一个生产-消费模型. Producer:生产 ...

  10. java反射使用和源码解析

    1         反射 1.1            什么是反射 正射:指的是我们知道类的定义和类中的方法名称,直接先创建对象,然后通过对象去调用方法.例如: Apple apple = new A ...