2016-09-29 167 views
1

我有一個類似於下面概述的文件夾結構。遍歷文件夾,Python中的文件的幾個子文件夾

Path 
| 
| 
+----SubDir1 
|  | 
|  +---SubDir1A 
|  |  | 
|  |  |----- FileA.0001.ext 
|  |  |----- ... 
|  |  |----- ... 
|  |  |----- FileA.1001.ext 
|  |  |----- FileB.0001.ext 
|  |  |----- ... 
|  |  |----- ... 
|  |  |----- FileB.1001.ext 
|  +---SubDir1B 
     | 
|  |  |----- FileA.0001.ext 
|  |  |----- ... 
|  |  |----- ... 
|  |  |----- FileA.1001.ext 
|  |  |----- FileB.0001.ext 
|  |  |----- ... 
|  |  |----- ... 
|  |  |----- FileB.1001.ext 
+----SubDir2 
|  | 
|  |----- FileA.0001.ext 
|  |----- ... 
|  |----- ... 
|  |----- FileA.1001.ext 
|  |----- FileB.0001.ext 
|  |----- ... 
|  |----- ... 
|  |----- FileB.1001.ext 

我希望能夠列出每個SubDir1和SubDir2

我看了網上,看到在os.walk for循環,類似於第一FILEA和第一FILEB:

import os 

rootDir = '.' 
for dirName, subdirList, fileList in os.walk(rootDir): 
    print('Found directory: %s' % dirName) 
    for fname in fileList: 
     print('\t%s' % fname) 
    # Remove the first entry in the list of sub-directories 
    # if there are any sub-directories present 
    if len(subdirList) > 0: 
     del subdirList[0 

但是,這似乎只適用於如果有一個文件直接在一個子目錄。我的問題是,有時子目錄內有一個額外的子目錄(!!)

有沒有人有任何想法如何解決這個問題?

+0

你說過我在網上看過,在for循環中看到os.walk,類似於'。那麼你是說你在問題中輸入的代碼不是你運行的代碼? –

+0

不,我已經使用這段代碼,並修改了其他代碼也沒有工作 –

回答

0

您的問題實際上是這兩行,刪除它們,你前人的精力被罰款:

if len(subdirList) > 0: 
    del subdirList[0] 

說明

他們所做的就是他們讓每一個目錄中的第一個子目錄之前消失os.walk有時間走它。因此,您對子目錄有奇怪的行爲並不奇怪。

下面是使用下面的樹的這種行爲的例證:

test0/ 
├── test10 
│ ├── test20 
│ │ └── testA 
│ ├── test21 
│ │ └── testA 
│ └── testA 
├── test11 
│ ├── test22 
│ │ └── testA 
│ ├── test23 
│ │ └── testA 
│ └── testA 
└── testA 

沒有有問題的線路:

Found directory: ./test/test0 
    testA 
Found directory: ./test/test0/test10 
    testA 
Found directory: ./test/test0/test10/test21 
    testA 
Found directory: ./test/test0/test10/test20 
    testA 
Found directory: ./test/test0/test11 
    testA 
Found directory: ./test/test0/test11/test22 
    testA 
Found directory: ./test/test0/test11/test23 
    testA 

隨着有問題的線路:

Found directory: ./test/test0 
    testA 
Found directory: ./test/test0/test11 
    testA 
Found directory: ./test/test0/test11/test23 
    testA 

因此,我們清楚地看到,由於「壞行」,第一行的兩個子文件夾test10test22已被完全忽略。