2013-02-10 74 views
0

我想要獲取包含mp3的當前目錄下的目錄列表。包含指定擴展名的目錄的返回列表

我可以使用os.walk輕鬆獲得文件列表。我可以使用os.path.join(os.path.abspath(root), file)輕鬆獲得完整路徑,但我只想要一個包含匹配目錄的列表。我嘗試過使用os.path.dirnameos.path.pardir,但是我得到的全部是'..'

import os 
l = [] 
for root, dirs, files in os.walk('.'): 
    for file in files: 
     if file.endswith('.mp3'): 
      l.append(os.path.dirname(file)) 

我可能錯過了一些明顯的東西?

乾杯。

回答

2

root已經給你在每個循環的目錄名稱;只需做出絕對的並添加到l列表。然後移動到下一個目錄(一個匹配是足夠了):

import os 
l = [] 
for root, dirs, files in os.walk('.'): 
    if any(file.endswith('.mp3') for file in files): 
     l.append(os.path.abspath(root)) 

any()返回True只要它發現在包含可迭代即True第一元件;因此以.mp3結尾的第一個文件將導致any()返回True,並將當前目錄添加到匹配列表中。

+0

非常感謝* – 2013-02-10 10:55:03