Another interesting python snippet
July 2nd, 2009 by craigetWell, I think it’s interesting anyway..
So today I was trying to express the idea “do something to all these files, unless the filename matches the list of things we don’t care about”. I have to do a BUNCH of find-and-replace kinda stuff in the next week on a couple thousand webpages, so my plan is to write a little script to make sure I don’t miss anything. Sometimes the script will turn up a false positive that I know I want to ignore..
EDIT – The following snippet doesn’t do quite what I thought it did.. more later..
There are at least three distinct and reasonable ways to do this in Python:
# skip if name matches any of these ignore = ["thing1", "thing2"] # Iterate over the strings, see if a substring matches # This is reasonably clear, but it seems long and requires a flag for filepath in dirwalk(path): found = False for item in ignore: if filepath.find(item) > 0: found = True break if found: continue # do stuff.. # The next two ways build a list of matches # If there are any matches then skip this file # This is a more functional style for filepath in dirwalk(path): if filter(lambda item: filepath.find(item) != -1, ignore): continue # do stuff.. # Another way to do the same thing for filepath in dirwalk(path): if [item for item in ignore if filepath.find(item) != -1]: continue # do stuff..
Interestingly, the last two use the same number of characters. I’m not sure which I prefer. While I suspect the final one would be considered the most Pythonic, I do have a soft spot for lambda. Eh, maybe someday when I’m not lazy I will see which is the fastest.. though that doesn’t really matter for my purposes.

Warning: call_user_func(ich_comments_plugin_cb) [function.call-user-func]: First argument is expected to be a valid callback in /home/maldroid/public_html/craiget.com/wp-includes/comment-template.php on line 1308