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

前端 未结 17 1375
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2020-11-22 15:54

    In python 3.5+

    from pathlib import Path
    sorted(Path('.').iterdir(), key=lambda f: f.stat().st_mtime)
    
    0 讨论(0)
  • 2020-11-22 15:54
    from pathlib import Path
    import os
    
    sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)
    

    or

    sorted(Path('./').iterdir(), key=os.path.getmtime)
    

    or

    sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)
    

    where m time is modified time.

    0 讨论(0)
  • 2020-11-22 15:56

    Here's my version:

    def getfiles(dirpath):
        a = [s for s in os.listdir(dirpath)
             if os.path.isfile(os.path.join(dirpath, s))]
        a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
        return a
    

    First, we build a list of the file names. isfile() is used to skip directories; it can be omitted if directories should be included. Then, we sort the list in-place, using the modify date as the key.

    0 讨论(0)
  • 2020-11-22 15:56
    # *** the shortest and best way ***
    # getmtime --> sort by modified time
    # getctime --> sort by created time
    
    import glob,os
    
    lst_files = glob.glob("*.txt")
    lst_files.sort(key=os.path.getmtime)
    print("\n".join(lst_files))
    
    0 讨论(0)
提交回复
热议问题