[?] sorting files by modification time.

Joshua Macy l0819m0v0smfm001 at sneakemail.com
Wed Oct 3 00:12:38 EDT 2001


Iñigo Serna wrote [about sorting files by mod time]:

> No, you can't do this. If several files have the same modification time,
> last one would overwrite previous ones.
> 
> 
> filenames = os.listdir(folder)
> statdict = {}
> for name in filenames:
>     path = os.path.join(folder, name)
>     modified = os.path.getmtime(path)
>     while statdict.has_key(modified):	# this is the trick:
>         modified += 0.1			# do not allow repeated keys
>     statdict[modified] = name
> 
> keylist = statdict.keys()
> keylist.sort()
> 
> filenames_sorted_bymtime = []
> for k in keylist:
>     filenames_sorted_bymtime.append(statdict[k])
> 


  That works, but loses information.  If you wanted to preserve the 
actual modification times, you could create a list of (mod-time, 
filename) tuples instead of a dictionary, and then just sort that:

filenames = os.listdir(folder)
statlist = []
for name in filenames:
   path = os.path.join(folder, name)
   modified = os.path.getmtime(path)
   statlist.append((modified, name))
statlist.sort()



As an added bonus, files with equal modification times will be sorted 
lexicographically (your algorithm preserves the unpredictable order that 
for name in filenames returns them in).

Joshua






More information about the Python-list mailing list