License Public Domain
Lines 28
Keywords
directory tree (2) os.walk (1) walk (1)
Permissions
Group Owner: iCapsid
Viewable by Everyone
Editable by All Siafoo Users
Hide
Need a quick chart or graph for your blog? Try our reStructured Text renderer. Join Siafoo Now or Learn More

Get Every File in a Directory Tree Atom Feed 0

In Brief Traverses a directory tree and returns every file (every non-directory) found. Unless requested, excludes directories that start with '.' (such as '.svn').... more
# 's
 1def walk(path, relative = False, dotdirs = False):
2 '''
3 Given a 'path', traverses the directory tree and returns every file (every non-directory) found.
4 If 'relative' is True, the path is not converted into an absolute path.
5 If 'dotdirs' is True, directories that start with a '.' are included.
6 Otherwise they and their contents are excluded.
7 '''
8
9 if not relative:
10 path = os.path.abspath(path)
11
12
13 if os.path.isfile(path):
14 return [path]
15
16 elif os.path.isdir(path):
17 files = []
18 for dirpath, dirnames, filenames in os.walk(path):
19 if not dotdirs:
20 # Modify list in place -- there is probably a better way to do this
21 for dir in dirnames:
22 if dir.startswith('.'):
23 dirnames.pop(dirnames.index(dir))
24
25 files.extend(os.path.join(dirpath, file) for file in filenames)
26 return files
27
28 else:
29 raise ValueError, 'Not sure how to handle that sort of file.'

Traverses a directory tree and returns every file (every non-directory) found. Unless requested, excludes directories that start with '.' (such as '.svn').

Just pass the path name and any keyword options: * If 'relative' is True, the path is not converted into an absolute path. * If 'dotdirs' is True, directories that start with a '.' are included. Otherwise they and their contents are excluded.

Comments

over 8 years ago (26 Jun 2008 at 05:36 PM) by Stou S.
Nice... I need this a couple of months ago for something... but now I can't remember wtf it was that I needed this for.