2013-07-24 128 views
0

我想在輸出中遞歸地顯示文件和文件夾結構。以遞歸方式列出目錄中的文件 - python

實際結構:

Root--| 
     | 
     DIRA--| 
      | 
      DIRC--File5 
      File3 
      File4 
     File1 
     File2 
     DIRB--| 
      | 
      No File 

預期輸出:

Root: 
File1 
File2 

Root/DIRA 
File3 
File4 

Root/DIRA/DIRC 
File5 


Root/DIRB 
No File Found 

我寫了下面的代碼下面。但需要輸入,如何修改它以獲得所需的輸出。

代碼

import os.path 

path = 'C:\\My\\path\\here' 

for root, dirnames, filenames in os.walk(path): 
    for subdirname in dirnames: 
     print subdirname 

    for filename in filenames: 
     print os.path.join(root, filename) 

實際輸出

DIRA 
DIRB 
C:\My\path\here\File1 
C:\My\path\here\File2 
DIRC 
C:\My\path\here\DIRA\File3 
C:\My\path\here\DIRA\File4 
C:\My\path\here\DIRA\DIRC\File5 
+0

縮進最後爲 – Jiminion

回答

0
import os 

path = 'Root' 
for root, dirnames, filenames in os.walk(path): 
    print root 
    for filename in filenames: 
     print filename 
    if not filenames: 
     print 'No File Found' 
    print 
+0

感謝隊友。做了小的修改,並獲得了預期的結果。 – misguided

相關問題