Welcome, guest | Sign In | My Account | Store | Cart

--> returns a list of files with a given extension in a given directory

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import os

class CheckExt:
    def __init__(self, ext):
        self.ext=ext
    def checkExt(self, file):
        if os.path.splitext(file)[-1]==self.ext: return 1

def getFilesByExt(dir, ext):
    ce = CheckExt(ext)
    return filter(ce.checkExt, os.listdir(dir))




if __name__ == '__main__':
    """ quick test to see if works """
    print getFilesByExt('.', '.py')
    raw_input('press any key') # if run by double click

Often have to do this, and thought filter() would be a more elegant solution than looping over directory contents. Wanted to use a lambda function but couldn't figure how to pass the ext in...

3 comments

Ian Bicking 17 years, 9 months ago  # | flag

6 more (single-expression) implementations.

import glob, os
glob(os.path.join(directory, '*%s' % extension))

[os.path.join(directory, fn)
 for fn in os.listdir(directory)
 if fn.endswith(extension)]

filter(lambda fn, ext=extension: fn.endswith(ext),
       map(lambda fn, dir=directory: os.path.join(dir, fn),
           os.listdir(directory)))

Or get the path module from http://www.jorendorff.com/articles/python/path/

from path import path
path(directory).listdir('*.gif')
[fn for fn in path(directory).listdir()
 where fn.ext = extension]
[fn for fn in path(directory).listdir()
 if fn.fnmatch('*.gif')]
Ivo Woltring 17 years, 8 months ago  # | flag

Just use the module glob for this purpose.

The module glob lets you do all these kind of stuff

See: http://IvoNet.nl > Development for other Python stuff
James Lockley (author) 17 years, 8 months ago  # | flag

Thanks. Thanks for that. I esp like the list comprehension with the endswidth --> had never come across that before.

James

Created by James Lockley on Fri, 5 Mar 2004 (PSF)
Python recipes (4591)
James Lockley's recipes (2)

Required Modules

Other Information and Tasks