S1M0N_H
S1M0N_H

Reputation: 139

Return list of directories containing specified extension

I'd like to get a list of directories below the current directory containing mp3's.

I can get the a list of the files easily enough using os.walk. I can get the full path easily enough using os.path.join(os.path.abspath(root), file), but I just want a list with of the matching directories. I've tried using os.path.dirname and os.path.pardir, but all I get with them is '..'.

import os
l = []
for root, dirs, files in os.walk('.'):
    for file in files:
         if file.endswith('.mp3'):
             l.append(os.path.dirname(file))

I'm probably missing something obvious?

Cheers.

Upvotes: 0

Views: 374

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121844

root already gives you the directory name in each loop; just make that absolute and add to the l list. Then move to the next directory (one match is enough):

import os
l = []
for root, dirs, files in os.walk('.'):
    if any(file.endswith('.mp3') for file in files):
        l.append(os.path.abspath(root))

any() returns True as soon as it finds the first element in the contained iterable that is True; so the first file that ends with .mp3 will result in any() returning True and the current directory is added to the list of matches.

Upvotes: 2

Related Questions