Skip to content

Instantly share code, notes, and snippets.

@nathanrosspowell
Created May 24, 2012 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanrosspowell/2781355 to your computer and use it in GitHub Desktop.
Save nathanrosspowell/2781355 to your computer and use it in GitHub Desktop.
Walk from a directory (up or down) yielding the results of the passed function.
import os
dir = "blog"
# Walk from a dir returning the results of function.
# The path below the dir should be set out in date format.
# path example: /YYYY/MM/DD/file.ext
# path example: /2012/01/30/file.txt
def walk_dates_and_apply( dir, function, desc ):
for walking in os.walk( dir, topdown = desc ):
walking[ 1 ].sort( reverse = desc )
for result in function( *walking, desc = desc ):
yield result
# Example function for returning latest/'up to date' files.
def newest_files( dirname, dirnames, filenames, desc = True ):
paths = [ os.path.join( dirname, x ) for x in filenames ]
t = os.path.getmtime
paths.sort( reverse = desc, cmp = lambda x,y: int( t( x ) - t( y ) ) )
for file in paths:
yield file
if __name__ == "__main__":
# Print out all of the file paths, newest to oldest.
for f in walk_dates_and_apply( dir, newest_files, True ):
print f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment