--> returns a list of files with a given extension in a given directory
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...
6 more (single-expression) implementations.
Or get the path module from http://www.jorendorff.com/articles/python/path/
Just use the module glob for this purpose.
Thanks. Thanks for that. I esp like the list comprehension with the endswidth --> had never come across that before.
James