0

我有一个像这样的文件夹系统:

    • 混音带 1
      • mp3
      • 子目录/
        • mp3
    • 混音带 2
      • mp3
      • 子目录/
        • mp3
    • 混音带 3
      • mp3
      • 子目录/
        • 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?

4

2 回答 2

0

为什么不做显而易见的事?检查它:

类似的东西(没有检查它的确切语法)

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


    for mp3 in mp3s:
        if os.path.dirname(os.path.join(mixtape, mp3)) == rootDir:
        continue
于 2013-11-02T17:27:13.043 回答
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 之前首先深入到文件夹层次结构中的两个级别。

此外,如果您在每个“子目录”文件夹中没有任何子文件夹,那么您可以在函数中使用 os.listdir() 而不是 os.walk() ,因为没有更多子文件夹可以遍历.

于 2013-11-02T17:39:03.677 回答