Create a filter for the audio and image files with python

Hello and welcome back. In this chapter, we will create two methods used to filter out the unwanted audio and image file. The rules of filtering are as follows.

  1. The file name cannot contain a blank space, the ‘-‘ or the ‘_’ or the ‘,’ or numbers.
  2. The file extension cannot contain a capital letter.
  3. Only a few valid audio or image file extensions are allowed to get past the filter.
  4. There must be a file extension.

Any rule violation will make the program returns False or else the program will return True.

Below is the methods that will act as the filter.

def is_audio(file_name):

    if(prelim(file_name) == False):
        return False

    audio = ['.mp3', '.flac', '.alac', '.aac']

    for ex in audio:
        if(ex in file_name):
            return True

    return False

def is_img(file_name):

    if(prelim(file_name) == False):
        return False

    img = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']

    for ex in img:
        if(ex in file_name):
            return True

    return False

def prelim(file_name):
    
    if(" " in file_name or "-" in file_name or "_" in file_name or "," in file_name):
        return False

    # no uppercase for the file extension
    try:
        index_ = file_name.index('.')
        if(file_name[index_:].isupper()):
            return False
    except ValueError:
        return False
    
    numbers = ['1','2','3','4','5','6','7','8','9','0']
    
    for num in numbers:
        if (num) in file_name[0:index_]:
            return False

OK, now let us try out the above program.

print(is_audio('x_.mp3')) // False
print(is_audio('x-.mp3')) // False
print(is_img('x10.gif'))  // False
print(is_img('x.PNG')) // False
print(is_img('x.png')) // True
print(is_audio('y,.flac'))  // False
print(is_img('x')) // False
print(is_audio('y.png')) // False
print(is_audio('y m c a.alac')) // False
print(is_audio('YOUNGMANYOUGOTNOPLACETOGO.alac')) // True

Well there you have it, we will start our next python project in the next chapter as I have promised you to.

Leave a Reply

avatar
  Subscribe  
Notify of