]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - src/FileUtils.py
Added the find_file_paths function to the FileUtils module.
[dead/census-tools.git] / src / FileUtils.py
1 """
2 Utility functions for working with the filesystem, generally modeled
3 after useful shell commands.
4 """
5
6 import os
7
8
9 def rm_f(path):
10 """
11 Remove (unlink) a file, ignoring any exceptions that may be
12 thrown.
13 """
14 try:
15 os.remove(path)
16 except:
17 pass
18
19
20 def mkdir_p(path, mode):
21 """
22 Create a directory hierarchy, ignoring any exceptions that may be
23 thrown.
24 """
25 try:
26 os.makedirs(path, mode)
27 except:
28 pass
29
30
31
32 def find_file_paths(root, target_filename, return_first = False):
33 """
34 Search beneath root for files named target_filename. If
35 return_first is True, then return as soon as a match is
36 found. Otherwise, return once all matching paths have been
37 found. Either way, the result is a list containing all matched
38 paths (even if we only matched one).
39 """
40 found_files = []
41
42 for folder, subfolders, files in os.walk(root):
43 for f in files:
44 if (f == target_filename):
45 if return_first:
46 return [os.path.join(folder, f)]
47 else:
48 found_files.append(os.path.join(folder, f))
49
50 return found_files