Script to Delete Directories without Music

After moving all my music with EasyTag creator I was left with a directory structure with tons of directories which had no music (but maybe .cue or .m3u files or maybe even subdirs). If you run this on the root of your music folder, it will try to fix it!

#!/usr/bin/python
import re, os, sys, shutil
"""Script to delete all subfolders of a folder that do not
contain music (at any subdirectory level).
 - Alex Knaust 10/25/2012
"""

musicRegex = re.compile(r"\.(flac|mp3|ogg|mp4|aac|alac|ape|wav)", re.IGNORECASE)
def music_match(fname):
    """Determine if a file is music (according to musicRegex)"""
    return musicRegex.match(os.path.splitext(fname)[-1])

def has_any_music(files):
    """Check if a list of filenames contains any music files (via music_match)"""
    for f in files:
        if music_match(f):
            return True
    return False
                
def get_nomusic_directories(srcdir):
    """Returns a list of subdirectories with no music in them" (at any level)"""
    results = []
    for f in os.listdir(srcdir):
        f = os.path.join(srcdir, f)
        if os.path.isdir(f):
            hasmusic = False
            for dirpath, dirnames, filenames in os.walk(f):
                if has_any_music(filenames):
                    hasmusic = True
                    break
            
            if not hasmusic:
                results.append(f)            
    return results
    
    
def main():
    if len(sys.argv) != 2:
        print('Pass the directory to be cleaned')
        exit(1)
    
    nomusic = get_nomusic_directories(sys.argv[1])
    ans = raw_input('Will delete %d Directories OK? y/n : ' % len(nomusic)) 
    
    if not ans.lower()[0] == 'y':
        print 'OK! exiting...'
        exit(0)
    
    for directory in nomusic:
        def printfails(func, path, errinf):
            print('Failed to remove "%s"' % path)
            
        shutil.rmtree(directory, onerror=printfails)
    
if __name__ == '__main__':
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>