tags:

views:

124

answers:

2

I'm trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension ".asp". What would be the best way to do this?

+5  A: 

You'll want to use os.walk which will make that trivial.

import os

asps = []
for root, dirs, files in os.walk(r'C:\web'):
    for file in files:
     if file.endswith('.asp'):
      asps.append(file)
Unknown
Or `asps = [(file for file in files if file.endswith('.asp')) for _,__,files in os.walk(path)]`, which I think would be the "Pythonic" way of doing it (although it's really just slightly shorter syntax for the exact same thing).
David Zaslavsky
1 liners are nice but aren't exactly Pythonic in readability.
Unknown
This recurses down directories but does not store the paths of the files.
hughdbrown
+3  A: 

walk the tree with os.walk and filter content with glob:

import os
import glob

asps = []
for root, dirs, files in os.walk('/path/to/dir'):
    asps += glob.glob(os.path.join(root, '*.asp'))

or with fnmatch.filter:

import fnmatch
for root, dirs, files in os.walk('/path/to/dir'):
    asps += fnmatch.filter(files, '*.asp')
SilentGhost
Like the os.path.join(). I imagine OP will find he needs complete path to the files found.
hughdbrown
When I did your second solution, it just searches the same directory repeatedly. I think it needs this: >>> asps=[]>>> p = r'C:\temp'>>> for root, dirs, files in os.walk(p):... asps += fnmatch.filter([os.path.join(root,file) for file in files], "*.txt")
hughdbrown
Ummm, not quite right. I have the same file in multiple directories under a root directory. It looks like the same directory searched repeatedly but isn't. it still would be better with the path attached, as in your first solution.
hughdbrown