[Tutor] Regex to find files ending with one of a given set of extensions

Steven D'Aprano steve at pearwood.info
Sun Feb 21 18:46:40 CET 2010


On Mon, 22 Feb 2010 04:23:04 am Dayo Adewunmi wrote:
> Hi all
>
> I'm trying use regex to match image formats:

Perhaps you should use a simpler way.

def isimagefile(filename):
    ext = os.path.splitext(filename)[1]
    return (ext.lower() in 
    ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'))


def findImageFiles():
    someFiles = [
    "sdfinsf.png","dsiasd.dgf","wecn.GIF","iewijiefi.jPg","iasjasd.py"]
    return filter(isimagefile, someFiles)


> $ python test.py
> Traceback (most recent call last):
>   File "test.py", line 25, in <module>
>     main()
>   File "test.py", line 21, in main
>     findImageFiles()
>   File "test.py", line 14, in findImageFiles
>     findImages = imageRx(someFiles)
> TypeError: '_sre.SRE_Pattern' object is not callable

The error is the line 

findImages = imageRx(someFiles)


You don't call regexes, you have to use the match or search methods. And 
you can't call it on a list of file names, you have to call it on each 
file name separately.

# untested
for filename in someFiles:
    mo = imageRx.search(filename)
    if mo is None:
        # no match
        pass
     else:
        print filename




-- 
Steven D'Aprano


More information about the Tutor mailing list