我有一個文件夾系統,像這樣:匹配的文件 - 蟒蛇
- 根
- 的Mixtape 1
- 的MP3
- 子DIR/
- 的MP3
- 混音帶2
- 的MP3
- 子DIR/
- 的MP3
- 混音帶3
- 的MP3
- 子DIR/
-
級
- 的MP3
- 的Mixtape 1
我期待創建的所有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,如果它在子目錄內呢?
如果這對於OP是顯而易見的,他們不會問這個問題。 – SethMMorton
表示沒有進攻的OP,但我認爲他正在尋找內置的方法或類似的東西 – alonisser