Know what you're getting – Unlike many sites, all our code is clearly licensed.
Join Siafoo Now
or
Learn More
Get Every File in a Directory Tree
| 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 |
| Language | Python |
# '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