2012-10-26 143 views
1

我正在嘗試使用os.walk()來瀏覽目錄。我目前的執行情況如下:Python通過目錄遞歸

print(".:") 
for dirname, dirnames, filenames in os.walk(path): 
    for filename in filenames: 
     print(os.path.join(dirname, filename)) 
    print() 
    for subdirname in dirnames: 
     print(os.path.join(dirname, subdirname) + ":") 

對於 「路徑」 我得到以下輸出:

.: 
./File5.py 
./File 3.py 
./File 1.py 

./directory 2: 
./directory 4: 
./Test Directory: 
./directory 2/player_career.csv 
./directory 2/File2.py 

./directory 4/test.txt 
./directory 4/Homework4.py 

./directory 4/__pycache__: 
./directory 4/__pycache__/File4.cpython-32.pyc 


./Test Directory/Test 3: 
./Test Directory/Test 2: 
./Test Directory/Test 3/ttt 

./Test Directory/Test 2/Untitled Document 2 
./Test Directory/Test 2/Untitled Document 

./Test Directory/Test 2/Untitled Folder: 
./Test Directory/Test 2/Untitled Folder/jjj 

,我期待的輸出爲:

.: 
./File5.py 
./File 3.py 
./File 1.py 

./directory 2: 

./directory 2/player_career.csv 
./directory 2/File2.py 

./directory 4: 

./directory 4/test.txt 
./directory 4/Homework4.py 

./directory 4/__pycache__: 

./directory 4/__pycache__/File4.cpython-32.pyc 

./Test Directory: 

./Test Directory/Test 2: 

./Test Directory/Test 2/Untitled Document 
./Test Directory/Test 2/Untitled Document 2 

./Test Directory/Test 2/Untitled Folder: 

./Test Directory/Test 2/Untitled Folder/jjj 

./Test Directory/Test 3: 

./Test Directory/Test 3/ttt 

如果我這樣做是遞歸的,我可以簡單地調用我找到的每個子目錄的函數,但是我很難找出使用os.walk()這樣做的優雅方法。

我的問題:我如何使用os.walk()

回答

8

不要立即打印出子目錄,而是打印出來,當你在目錄實際上是得到上面的輸出。

一個例子:

for dirname, dirnames, filenames in os.walk(path): 
    print() 
    print(dirname + ":") 
    for filename in filenames: 
     print(os.path.join(dirname, filename)) 

的方式os.walk作品,試圖打印所有的目錄名立即在你讓他們在dirnames的時間不會給你想要的順序。

+0

這使得我想要實現的東西更有意義。非常感謝你。我誤解了os.walk()的內部工作原理。 –