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?
views:
124answers:
2
+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
2009-08-13 20:57:08
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
2009-08-13 21:01:03
1 liners are nice but aren't exactly Pythonic in readability.
Unknown
2009-08-13 21:02:38
This recurses down directories but does not store the paths of the files.
hughdbrown
2009-08-13 22:12:41
+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
2009-08-13 20:57:42
Like the os.path.join(). I imagine OP will find he needs complete path to the files found.
hughdbrown
2009-08-13 22:01:42
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
2009-08-13 22:09:26
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
2009-08-13 22:35:57