Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅匹配子目录中的文件-python_Python_Subdirectory_Os.walk - Fatal编程技术网

仅匹配子目录中的文件-python

仅匹配子目录中的文件-python,python,subdirectory,os.walk,Python,Subdirectory,Os.walk,我有一个这样的文件夹系统: 根 混音带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 t

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

    • 混音带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文件。。。我只希望它们包含在“sub dir”中


那么,我如何修改fileList函数,使其仅在mp3位于子目录中时附加它呢?

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

类似于(没有检查它的确切synatx)


一种可能的解决方案是对fileList()进行以下修改:

为了澄清,这个成语:

next(os.walk(some_dir))[1]
…返回某个目录中的子目录名称列表

换句话说,在搜索MP3之前,上面的代码首先向下跳入两层文件夹heirarchy


此外,如果每个“sub-dir”文件夹中没有任何子文件夹,则可以在函数中的该点使用os.listdir()而不是os.walk(),因为没有其他子文件夹可遍历。

如果OP明显看到了这一点,他们就不会问这个问题。这对OP没有冒犯之意,但我认为他正在寻找一种内置的方法或类似的东西
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]