Created
May 24, 2012 12:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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