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
  • 37,180
  • 60
  • 149
  • 218

3 Answers3

17

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,642
  • 1
  • 23
  • 37
Raymond Hettinger
  • 199,887
  • 59
  • 344
  • 454
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,578
  • 32
  • 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,581
  • 1
  • 12
  • 24