我有一个像这样的文件夹系统:
- 根
- 混音带 1
- mp3
- 子目录/
- mp3
- 混音带 2
- mp3
- 子目录/
- mp3
- 混音带 3
- mp3
- 子目录/
- mp3
- 混音带 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?