File dates are best sorted by the seconds since epoch value. The elimination of exact duplicates (time and path/name) makes not much sense, since they shouldn't even exist ...
# sorts files by modifed date,
# pulls 6 most recent files,
# and delete all others.
#created by dan holding v0.1 (03 Aug 2010)
import os, glob, time, sets
root = '.'
date_file_list = []
for folder in glob.glob(root):
print "folder =", folder
# select the type of file, for instance *.bat or all files *.*
for file in glob.glob(folder + '\*.txt*'):
stats = os.stat(file)
# seconds since epoch starting midnight of 1/1/1970
lastmod_seconds = stats[8]
# use seconds first to sort the time
date_file_tuple = lastmod_seconds, file
date_file_list.append(date_file_tuple)
# create a set to eliminate duplicate files
# with matching seconds and path/name
date_file_set = set(date_file_list)
# convert set back to a list
date_file_list = list(date_file_set)
# latest modified date (in seconds) now first
date_file_list.sort(reverse = True)
# test
print (len(date_file_list))
print (len(date_file_set))
print('-'*70)
# show six most recent files
for lastmod_seconds, path in date_file_list[:6]:
folder, file_name = os.path.split(path)
# convert seconds to time tuple
lastmod_tuple = time.localtime(lastmod_seconds)
# convert time tuple to MM/DD/YYYY HH:MM:SS format
file_date = time.strftime("%m/%d/%y %H:%M:%S", lastmod_tuple)
print "%-40s %s" % (file_name, file_date) vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417