Script Collection
Other
Directory Watcher - Recursive | Directory Watcher - Recursive |
|
|
|
|
Inspired by Directory Watcher. This will watch all files and directories under the path you specify.
This utilizes os.walk() instead of os.listdir. Due to the list of tuples produced by that function, it's difficult to use a single comprehension to produce a list of values without having nested lists. Fortunately, you can overcome this limitation by not using the output of the list comprehension. Rather, simply append the value in each iteration to a list outside the comprehension...just make sure to reset it each time or use a sub-routine.
Prior to all examples below: path = "c:\\temp" flist = []Various list comprehensions that can be used based on above: 1) All files:
[[flist.append(elem[0] + "\\" + f)
for f in elem[2] if elem[2]] for elem in os.walk(path, True)]
2) All sub-directories:
[[flist.append(elem[0] + "\\" + f)
for f in elem[1] if elem[1]] for elem in os.walk(path, True)]
The two above can't be done in a single list comprehension...or can they? One could just use two separate lists, e.g. f_list and d_list, and compare them separately or add them together before comparing.There are some looping issues when adding them to one comprehension. To get around the looping problems, we will put each append section within a tuple, so they're each executed on each loop. The tuple doesn't matter since we're capturing the comprehension output indirectly. 3) All files and sub-directories: [([flist.append(elem[0] + "\\" + f) for f in elem[2] if elem[2]], [flist.append(elem[0] + "\\" + f) for f in elem[1] if elem[1]]) for elem in os.walk(path, True)]4) All files and sub-directories (including root): [([flist.append(elem[0] + "\\" + f) for f in elem[2] if elem[2]], flist.append(elem[0])) for elem in os.walk(path, True)]Here's a little sample program that uses these last two. import os, time def recurse(path, root): flist = [] noval = [] if root: noval = [([flist.append(elem[0] + "\\" + f) for f in elem[2] if elem[2]], flist.append(elem[0])) for elem in os.walk(path, True)] return flist else: noval = [([flist.append(elem[0] + "\\" + f) for f in elem[2] if elem[2]], [flist.append(elem[0] + "\\" + f) for f in elem[1] if elem[1]]) for elem in os.walk(path, True)] return flist path_to_watch = "c:\\temp" before = recurse(path_to_watch, False) for i in range(1, 15): time.sleep(5) after = recurse(path_to_watch, False) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if added: print "Added: ", ", ".join(added) if removed: print "Removed: ", ", ".join(removed) before = after |
|
| Last Updated ( Sunday, 26 March 2006 ) |
| Next > |
|---|
Hint: For syntax highlighting and correct Python intendation place your code between html tags <pre> and </pre>.