How to check if a directory has music files in python?

Viewed 533

We can check whether a file or path exist using os.path.exists(path_name) and whether it is a file or directory using os.path.isfile() and os.path.isdir() respectively after importing os module in python. But how can we check if the directory specified contains particular types of files (music, image, video, doc, xls etc.)

2 Answers

One way is to use os.listdir(path) to get a list of all entries in that directory, then loop through that list to identify the filetypes.

Here's an example using most audio file extensions:

import os

path = "./" #path to your directory
dir = os.listdir(path)

audio_extenions =["3gp","aa","aac","aax","act","aiff","alac","amr","ape","au","awb","dct","dss","dvf","flac","gsm","iklax","ivs","m4a","m4b","m4p","mmf","mp3","mpc","msv","nmf","ogg","oga","mogg","opus","ra","rm","raw","rf64","sln","tta","voc","vox","wav","wma","wv","webm","8svx","cda"]

for file in dir:
    if os.path.isfile(file):
        if file.endswith(tuple(audio_extenions)):
            #directory contains audio files

Further code could be implemented to determine if all files in a directory are the same type or not.

You can try filtering os.listdir(), such as if you want to check if the C:\Test folder has .mp3 or .mp4 files:

import os
any(True for x in os.listdir(r'C:\Test') if x.split(".")[-1] in ['mp3','mp4','ogg','wav'])
Related