zoukankan      html  css  js  c++  java
  • os.walk()方法 分类: python Module python基础学习 2013-08-09 07:59 342人阅读 评论(0) 收藏

    os.sep 获取目录分隔符

    =================================================================

    os.makedirs() os.removedirs()

    os.makedirs()函数用于创建上下级关联的目录、子目录,类似于linux命令 mkdir -p a/b/c。例如os.makedirs("a/b/c")的结果:


    与os.makedirs()对应的是os.removedirs()函数,用于删除 空的目录。os.removedirs("a/b/c")即可删除 空的目录.例如 a/b/c  a目录非空,b、c目录均为空,则removedirs可以同时删除b/c目录

    如果要删除非空的目录,可以使用shutil模块,shutil.rmtree("a")即可强制删除目录a

    ===================================================================


    #coding:utf-8
    
    import os
    def main():
        '''
        root 是起始路径,且是绝对路径
        dirs 起始路径下的目录列表
        files 起始路径下的文件列表
        '''
        for root,dirs,files in os.walk(r'g:'):
    
            for f in files:
                print '*'*10,root,'*'*10
                print os.path.join(root,f)
    
    if __name__ == '__main__':
        main()
    

    部分结果:

    ********** g: **********
    g:模块5.py
    ********** g: **********
    g:空行输出特殊字符.py
    ********** g:$RECYCLE.BINS-1-5-21-2589521740-3335953511-3928509256-1000 **********
    g:$RECYCLE.BINS-1-5-21-2589521740-3335953511-3928509256-1000desktop.ini
    ********** g:1 **********
    g:1a.a
    ********** g:1 **********
    g:1aa.aa
    ********** g:1 **********
    g:1新建文本文档.txt
    ********** g:1 **********
    g:1齐秦-原来的我.MP3
    ********** g:auto **********
    g:autoauto.py
    ********** g:auto **********
    g:autoauto_suit.py
    ********** g:auto **********
    g:autodynamic.py


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


    先看下代码:



    import os

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



    下面是输出:

    c:ant
    c:antin
    c:antdocs
    c:antdocsant2
    c:antdocsantlibs
    c:antdocsantlibsantunit
    c:antdocsantlibscompress
    c:antdocsantlibsdotnet
    c:antdocsantlibsprops
    c:antdocsantlibssvn
    c:antdocsimages
    c:antdocsmanual
    c:antdocsmanualapi
    c:antdocsmanualapiorg
    c:antdocsmanualapiorgapache
    c:antdocsmanualapiorgapache ools
    c:antdocsmanualapiorgapache oolsant
    c:antdocsmanualapiorgapache oolsantdispatch
    c:antdocsmanualapiorgapache oolsantfilters


    后面还有很长.

    如果不使用这个方法,遍历同样能达到效果.不过使用 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
  • 相关阅读:
    Asp.NET 4.0 ajax实例DataView 模板编程1
    ASP.NET 4.0 Ajax 实例DataView模板编程 DEMO 下载
    部分东北话、北京话
    .NET 培训课程解析(一)
    ASP.NET 4.0 Ajax 实例DataView模板编程2
    ASP.NET Web Game 架构设计1服务器基本结构
    ASP.NET Web Game 构架设计2数据库设计
    TFS2008 基本安装
    Linux上Oracle 11g安装步骤图解
    plsql developer远程连接oracle数据库
  • 原文地址:https://www.cnblogs.com/think1988/p/4628106.html
Copyright © 2011-2022 走看看