7

Possible Duplicate:
In Python, fastest way to build a list of files in a directory with a certain extension

I currently am using os.walk to recursively scan through a directory identifying .MOV files

def fileList():
    matches = []
    for root, dirnames, filenames in os.walk(source):
        for filename in fnmatch.filter(filenames, '*.mov'):
            matches.append(os.path.join(root, filename))
    return matches

How can I extend this to identify multiple files, e.g., .mov, .MOV, .avi, .mpg?

Thanks.

Community
  • 1
  • 1
ensnare
  • 40,069
  • 64
  • 158
  • 224

3 Answers3

20

Try something like this:

def fileList(source):
    matches = []
    for root, dirnames, filenames in os.walk(source):
        for filename in filenames:
            if filename.endswith(('.mov', '.MOV', '.avi', '.mpg')):
                matches.append(os.path.join(root, filename))
    return matches
Ahmed
  • 2,825
  • 1
  • 25
  • 39
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
2

An alternative using os.path.splitext:

for root, dirnames, filenames in os.walk(source):
    filenames = [ f for f in filenames if os.path.splitext(f)[1] in ('.mov', '.MOV', '.avi', '.mpg') ]
    for filename in filenames:
        matches.append(os.path.join(root, filename))
return matches
DRH
  • 7,868
  • 35
  • 42
2
pattern = re.compile('.*\.(mov|MOV|avi|mpg)$')

def fileList(source):
   matches = []
   for root, dirnames, filenames in os.walk(source):
       for filename in filter(lambda name:pattern.match(name),filenames):
           matches.append(os.path.join(root, filename))
   return matches
Jhonathan
  • 1,611
  • 2
  • 13
  • 24