【问题标题】:match files in sub directories only - python仅匹配子目录中的文件 - python
【发布时间】:2013-11-02 17:14:09
【问题描述】:

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

    • 混音带 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 位于子目录中时附加它?

【问题讨论】:

    标签: python subdirectory os.walk


    【解决方案1】:

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

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

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

    【讨论】:

    • 如果这对 OP 来说是显而易见的,他们就不会问这个问题了。
    • 无意冒犯 OP,但我认为他正在寻找内置方法或类似的东西
    【解决方案2】:

    一种可能的解决方案是对 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-01-07
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2021-05-28
      • 2014-10-01
      相关资源
      最近更新 更多