遍歷文件夾是一個很經常使用的功能吧。這裏分別用兩種方法實現: ide
第一種:使用os.walk:
測試
- # -*- coding: utf-8 -*-
- 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:spa
- # -*- 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)
這兩種到底有什麼區別呢?xml
這裏先創建一個測試目錄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
下面經過運行以下代碼:utf-8
- Test1('E:\TEST')
- print '======================================='
- Test2('E:\TEST')
輸出結果爲:string
- >>>
- 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
- >>>
能夠看出,對於第一種方法,輸出老是先文件夾後文件名的,對於第二種,則是按照目錄樹結構以及按照首字母排序進行輸出的。it
另外以前打印出的目錄樹其實就是經過對第二種方法進行稍微修改實現的,以下:class
- 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)