Search code examples
pythonregexstringcase-insensitiveends-with

How to perform a case-insensitive search for files of a given suffix?


I'm looking for the equivalent of find $DIR -iname '*.mp3', and I don't want to do the kooky ['mp3', 'Mp3', MP3', etc] thing. But I can't figure out how to combine the re*.IGNORECASE stuff with the simple endswith() approach. My goal is to not miss a single file, and I'd like to eventually expand this to other media/file types/suffixes.

import os
import re
suffix = ".mp3"

mp3_count = 0

for root, dirs, files in os.walk("/Volumes/audio"):
    for file in files:
        # if file.endswith(suffix):
        if re.findall('mp3', suffix, flags=re.IGNORECASE):
            mp3_count += 1

print(mp3_count)

TIA for any feedback


Solution

  • You can try this :)

    import os
    # import re
    suffix = "mp3"
    
    mp3_count = 0
    
    for root, dirs, files in os.walk("/Volumes/audio"):
        for file in files:
            # if file.endswith(suffix):
            if file.split('.')[-1].lower() == suffix:
                mp3_count += 1
    
    print(mp3_count)
    

    Python's string.split() will separate the string into a list, depending on what parameter is given, and you can access the suffix by [-1], the last element in the list