[python]怎么样用Python读取一个目录树-os.walk入门

来源:互联网 发布:数据与信息的关系是 编辑:程序博客网 时间:2024/05/29 18:51

      原文: http://pythoncentral.org/how-to-traverse-a-directory-tree-in-python-guide-to-os-walk/
  
       当你使用如Python这样一门编辑脚本语言的时候,你会发现自己经常会做一件事情,就是浏览文件目录结构和处理文件。然而有很多方法去做这件事情,Pyhton内建函数让这件事情变得轻而易举。

       基本的目录遍历:

          这里有个遍历目录的简单例子,打印出每个目录所包含的文件:

# Import the os module, for the os.walk functionimport os # Set the directory you want to start fromrootDir = '.'for dirName, subdirList, fileList in os.walk(rootDir):    print('Found directory: %s' % dirName)    for fname in fileList:        print('\t%s' % fname)

           os.walk 关注这些细节,每次循环都会得到3样东西:
          dirName: 找到下一个目录
          subdirList: 当前目录的所有子目录
          fileList: 当前目录下的所有文件
          我们将会得到向下面似的目录:
 
+--- test.py|+--- [subdir1]|     ||     +--- file1a.txt|     +--- file1b.png|+--- [subdir2]|+--- file2a.jpeg+--- file2b.html


         上面这些代码的输出如下:
       
Found directory: .        file2a.jpeg        file2b.html        test.pyFound directory: ./subdir1        file1a.txt        file1b.pngFound directory: ./subdir2


       改变下读取目录树的方式:

           默认的,Python会自上而下的顺序遍历目录树,然后才会进入下面任意一个子目录。我们可  以从上面的输出看出来,当前的(.)目录打印完了,才会打印2个子目录。
            如果我们像要倒过来这个顺序就可以在os.walk加一个 topdown 参数:
 
import os rootDir = '.'for dirName, subdirList, fileList in os.walk(rootDir, topdown=False):    print('Found directory: %s' % dirName)    for fname in fileList:        print('\t%s' % fname)

           输出:

Found directory: ./subdir1        file1a.txt        file1b.pngFound directory: ./subdir2Found directory: .        file2a.jpeg        file2b.html        test.py


            现在我们先看到子目录的文件,然后才向上到上一级目录。


         

        有选择的读取目录:

              到现在为止的例子都是简单的读取全部的目录,但是os.walk也可以让我们跳过目录树的某些部分。os.walk返回的每个目录,都提供了起子目录的列表,如果我们修改这个列表,就能控制它向下 读取的子目录,让我们改变下上面的例子足以让程序跳过某些目录。

            

import os rootDir = '.'for dirName, subdirList, fileList in os.walk(rootDir):    print('Found directory: %s' % dirName)    for fname in fileList:        print('\t%s' % fname)    # Remove the first entry in the list of sub-directories    # if there are any sub-directories present    if len(subdirList) > 0:        del subdirList[0]

Found directory: .
        file2a.jpeg
        file2b.html
        test.py
Found directory: ./subdir2

             我们可以看到 子目录subdir1 被跳过了。

        

本文出自 orangleliu笔记本 博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/8734555