2013-11-02 135 views
0

我有一個文件夾系統,像這樣:匹配的文件 - 蟒蛇

    • 的Mixtape 1
      • 的MP3
      • 子DIR/
        • 的MP3
    • 混音帶2
      • 的MP3
      • 子DIR/
        • 的MP3
    • 混音帶3
      • 的MP3
      • 子DIR/
        • 的MP3

我期待創建的所有MP3文件的列表(從子目錄的唯一的),然後播放從該列表中隨機MP3。

所以,我想出了下面的代碼:

import os 
import random 
import subprocess 

# Set the root dir for mixtapes 
rootDir = 'mixtapes' 

# Function to make a list of mp3 files 
def fileList(rootDir): 
    matches = [] 
    for mixtape, subdir, mp3s in os.walk(rootDir): 
     for mp3 in mp3s: 
      if mp3.endswith(('.mp3', '.m4a')): 
       matches.append(os.path.join(mixtape, mp3)) 
    return matches 

# Select one of the mp3 files from the list at random 
file = random.choice(fileList(rootDir)) 

print file 

# Play the file 
subprocess.call(["afplay", file]) 

然而,這段代碼在所有名爲.mp3或.m4a的文件遞歸拉......我只希望他們,如果他們在其中所包含的「子目錄」。

那麼,如何修改fileList函數來只追加mp3,如果它在子目錄內呢?

回答

0

爲什麼不明顯?檢查它:

像(沒有檢查它的確切synatx)

for mixtape, subdir, mp3s in os.walk(rootDir): 


    for mp3 in mp3s: 
     if os.path.dirname(os.path.join(mixtape, mp3)) == rootDir: 
     continue 
+0

如果這對於OP是顯而易見的,他們不會問這個問題。 – SethMMorton

+0

表示沒有進攻的OP,但我認爲他正在尋找內置的方法或類似的東西 – alonisser

0

一個可能的解決方案是以下修改的fileList():

def fileList(rootDir): 
    matches = [] 
    for d1 in next(os.walk(rootDir))[1]: 
     for d2 in next(os.walk(os.path.join(rootDir, d1)))[1]: 
      for mixtape, subdir, mp3s in os.walk(os.path.join(rootDir, d1, d2)): 
       for mp3 in mp3s: 
        if mp3.endswith(('.mp3', '.m4a')): 
         matches.append(os.path.join(mixtape, mp3)) 
    return matches 

對於澄清,此成語:

next(os.walk(some_dir))[1] 

...返回some_dir中的子目錄名稱列表。

換句話說,上面的代碼首先在搜索mp3之前將文件夾水平分爲兩層。另外,如果在每個「sub-dir」文件夾中沒有任何子文件夾,則可以使用os.listdir()而不是os。在該函數中的walk(),因爲沒有更多的子文件夾可以遍歷。