Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 895
MagicToaster Avatar asked Dec 06 '22 13:12

MagicToaster


1 Answers

Don't bother with os.walk. Learn to use the easier, awesome pathlib.Path instead. Like so:

from pathlib import Path

suffix = ".mp3"

mp3_count = 0

p = Path('Volumes')/'audio': # note the easy path creation syntax
# OR even:
p = Path()/'Volumes'/'audio': 

for subp in p.rglob('*'): #  recursively iterate all items matching the glob pattern
    # .suffix property refers to .ext extension
    ext = subp.suffix
    # use the .lower() method to get lowercase version of extension
    if ext.lower() == suffix: 
        mp3_count += 1

print(mp3_count)

"One-liner", if you're into that sort of thing (multiple lines for clarity):

sum(1 for subp in (Path('Volumes')/'audio').rglob('*')
     if subp.suffix.lower() == suffix)
like image 79
Rick supports Monica Avatar answered Jan 08 '23 10:01

Rick supports Monica