[?] sorting files by modification time.

Quinn Dunkan quinn at ngwee.ugcs.caltech.edu
Thu Oct 4 00:30:44 EDT 2001


On 03 Oct 2001 06:24:00 GMT, Julius Welby <jwelby at waitrose.com> wrote:
>"Iñigo Serna" <inigoserna at terra.es> wrote in message
>news:mailman.1002062407.8789.python-list at python.org...
>Hi,
>
>En mar, 2001-10-02 a 21:48, Julius Welby escribió:
>> Get a listing of the file names using os.listdir for the folder, then you
>> can do something like:
>>
>> for name in filenames:
>>     path = os.path.join(folder, name)
>>     modified = os.path.getmtime(path)
>>     statdict[modified] = name
>>     keylist = statdict.keys()
>
>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])

Why get so complicated?

def files(d):
    # os.listdir's behaviour is usually inconvenient for me so this is a handy
    # utility
    return [ os.path.join(d, fn) for fn in os.listdir(d) ]

folder = '/foo/bar/baz'
a = [ (os.path.mtime(fn), fn) for fn in files(folder) ]
a.sort()
sorted_files = [ x[1] for x in a ]



More information about the Python-list mailing list