遍历文件夹是一个很常用的功能吧。这里分别用两种方法实现:
第一种:使用os.walk:
import os def Test1(rootDir): list_dirs = os.walk(rootDir) for root, dirs, files in list_dirs: for d in dirs: print os.path.join(root, d) for f in files: print os.path.join(root, f)
第二种:使用os.listdir:
# -*- coding: utf-8 -*- import os def Test2(rootDir): for lists in os.listdir(rootDir): path = os .path.join(rootDir, lists) print path if os.path.isdir(path): Test2(path)
这两种到底有什么区别呢?
这里先建立一个测试目录E:\test,目录结构如下:
E:\TEST │--A │ │--A-A │ │ │--A-A-A.txt │ │--A-B.txt │ │--A-C │ │ │--A-B-A.txt │ │--A-D.txt │--B.txt │--C │ │--C-A.txt │ │--C-B.txt │--D.txt │--E
下面通过运行如下代码:
Test1( 'E:\TEST' ) print '=======================================' Test2('E:\TEST' )
输出结果为:
>>> E:\TEST\A E:\TEST\C E:\TEST\E E:\TEST\B.txt E:\TEST\D.txt E:\TEST\A\A-A E:\TEST\A\A-C E:\TEST\A\A-B.txt E:\TEST\A\A-D.txt E:\TEST\A\A-A\A-A-A.txt E:\TEST\A\A-C\A-B-A.txt E:\TEST\C\C-A.txt E:\TEST\C\C-B.txt ======================================= E:\TEST\A E:\TEST\A\A-A E:\TEST\A\A-A\A-A-A.txt E:\TEST\A\A-B.txt E:\TEST\A\A-C E:\TEST\A\A-C\A-B-A.txt E:\TEST\A\A-D.txt E:\TEST\B.txt E:\TEST\C E:\TEST\C\C-A.txt E:\TEST\C\C-B.txt E:\TEST\D.txt E:\TEST\E >>>
可以看出,对于第一种方法,输出总是先文件夹后文件名的,对于第二种,则是按照目录树结构以及按照首字母排序进行输出的。
另外之前打印出的目录树其实就是通过对第二种方法进行稍微修改实现的,如下:
def Test3(rootDir, level= 1 ): if level== 1 : print rootDir for lists in os.listdir(rootDir): path = os.path.join(rootDir, lists) print '│ ' *(level- 1 )+ '│--' +lists if os.path.isdir(path): Test3(path, level+1 )