[Tutor] scratching my head

Peter Otten __peter__ at web.de
Wed Aug 5 08:43:45 CEST 2015

Laura Creighton wrote:

> In a message of Mon, 03 Aug 2015 18:22:32 +1000, Cameron Simpson writes:
>>That depends. This is the tutor list; we're helping Clayton debug his code
>>as an aid to learning. While it's good to know about the facilities in the
>>standard library, pointing him directly at fnmatch (which I'd entirely
>>forgotten) is the "give a man a fish" approach to help; a magic black box
>>to do the job for him.
>>Besides, I'm not sure fnmatch is much better for his task than the more
>>direct methods being discussed.
> And I am certain.  It works exactly as he said he wanted -- a less
> cumbersome way to solve this problem, which he thought would be done
> some way with a for loop, looping over extensions, instead of the
> cumbersome way he is doing things.

I suppose you have some way in mind to simplify

# version 1, splitext()
import os

filenames = ["foo.jpg", "bar.PNG", "baz.txt"]
EXTENSIONS = {".jpg", ".png"}
matching_filenames = [
    name for name in filenames 
    if os.path.splitext(name)[1].lower() in EXTENSIONS]

with fnmatch. I can only come up with

# version 2, fnmatch()
import fnmatch
filenames = ["foo.jpg", "bar.PNG", "baz.txt"]
GLOBS = ["*.jpg", "*.png"]
matching_filenames = [
    name for name in filenames 
    if any(fnmatch.fnmatch(name.lower(), pat) for pat in GLOBS)]

but I don't think that's simpler. Can you enlighten me?

Digression: I don't know if str.endswith() was already suggested. I think 
that is a (small) improvement over the first version

# version 3, endswith()
filenames = ["foo.jpg", "bar.PNG", "baz.txt"]
EXTENSIONS = (".jpg", ".png")
matching_filenames = [
    name for name in filenames 
    if name.lower().endswith(EXTENSIONS)]

More information about the Tutor mailing list