How do you get a directory listing sorted by creation date in python?

前端 未结 17 1401
忘了有多久
忘了有多久 2020-11-22 15:14

What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?

17条回答
  •  死守一世寂寞
    2020-11-22 15:54

    Here's a one-liner:

    import os
    import time
    from pprint import pprint
    
    pprint([(x[0], time.ctime(x[1].st_ctime)) for x in sorted([(fn, os.stat(fn)) for fn in os.listdir(".")], key = lambda x: x[1].st_ctime)])
    

    This calls os.listdir() to get a list of the filenames, then calls os.stat() for each one to get the creation time, then sorts against the creation time.

    Note that this method only calls os.stat() once for each file, which will be more efficient than calling it for each comparison in a sort.

提交回复
热议问题