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

前端 未结 17 1642
忘了有多久
忘了有多久 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:53

    I've done this in the past for a Python script to determine the last updated files in a directory:

    import glob
    import os
    
    search_dir = "/mydir/"
    # remove anything from the list that is not a file (directories, symlinks)
    # thanks to J.F. Sebastion for pointing out that the requirement was a list 
    # of files (presumably not including directories)  
    files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
    files.sort(key=lambda x: os.path.getmtime(x))
    

    That should do what you're looking for based on file mtime.

    EDIT: Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like:

    import os
    
    search_dir = "/mydir/"
    os.chdir(search_dir)
    files = filter(os.path.isfile, os.listdir(search_dir))
    files = [os.path.join(search_dir, f) for f in files] # add path to each file
    files.sort(key=lambda x: os.path.getmtime(x))
    

提交回复
热议问题