2013-11-27 49 views
0

我想遍歷頂層目錄的子目錄。 對於每個子目錄,我想走到它的子目錄中,然後走到子目錄的文件中。用特定的順序用os.walk遍歷子目錄

我已經看到有關os.walk的帖子,但花了幾個早上乘坐火車的時候,我一直沒能想出解決方案。

我已經檢查了os.walk的python文檔,它沒有幫助我。

對於澄清,這裏是目錄結構:

topdir 
    -> dirLesson1 
      -> dirLanguageA 
       -> file1 
       -> file2 
      -> dirLanguageB 
       -> file1 
       -> file2 
    -> dirLesson2 
      -> dirLanguageA 
       -> file1 
       -> file2 
      -> dirLanguageB 
       -> file1 
       -> file2 

這裏是僞代碼:

for dirLesson in topdir 
      # do something with dirLesson 
      for dirLanguage in dirLesson 
       # do something with dirLanguage 
       for file in dirLanguage 
         #do something with file 

我是新來的Python,所以任何幫助,將不勝感激。

回答

0
import os 

def getSubDirs(dir): 
    return [os.path.join(dir,name) for name in os.listdir(dir) 
      if os.path.isdir(os.path.join(dir, name))] 

def getSubFiles(dir): 
    return [os.path.join(dir,name) for name in os.listdir(dir) 
      if os.path.isfile(os.path.join(dir, name))] 


indir = "/topdir" 
subDirArr = [] 
subSubDirArr = [] 
subSubFileArr = [] 

subDirArr.extend(getSubDirs(indir)) 

for dir in subDirArr: 
    subSubDirArr.extend(getSubDirs(dir)) 

for dir in subSubDirArr: 
    subSubFileArr.extend(getSubFiles(dir)) 

print "Here i am doing operation on level1 dirs"  
for dir in subDirArr: 
    print os.path.basename(dir) 

print "Here i am doing operation on level2 dirs"  
for dir in subSubDirArr: 
     print os.path.basename(dir) 

print "Here i am doing operation on level3 files" 
for file in subSubFileArr: 
     print os.path.basename(file) 
+0

非常感謝! –