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

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

    Without changing directory:

    import os    
    
    path = '/path/to/files/'
    name_list = os.listdir(path)
    full_list = [os.path.join(path,i) for i in name_list]
    time_sorted_list = sorted(full_list, key=os.path.getmtime)
    
    print time_sorted_list
    
    # if you want just the filenames sorted, simply remove the dir from each
    sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
    print sorted_filename_list
    
    0 讨论(0)
  • 2020-11-22 15:35

    There is an os.path.getmtime function that gives the number of seconds since the epoch and should be faster than os.stat.

    import os 
    
    os.chdir(directory)
    sorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime)
    
    0 讨论(0)
  • 2020-11-22 15:35
    sorted(filter(os.path.isfile, os.listdir('.')), 
        key=lambda p: os.stat(p).st_mtime)
    

    You could use os.walk('.').next()[-1] instead of filtering with os.path.isfile, but that leaves dead symlinks in the list, and os.stat will fail on them.

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

    For completeness with os.scandir (2x faster over pathlib):

    import os
    sorted(os.scandir('/tmp/test'), key=lambda d: d.stat().st_mtime)
    
    0 讨论(0)
  • 2020-11-22 15:42

    This was my version:

    import os
    
    folder_path = r'D:\Movies\extra\new\dramas' # your path
    os.chdir(folder_path) # make the path active
    x = sorted(os.listdir(), key=os.path.getctime)  # sorted using creation time
    
    folder = 0
    
    for folder in range(len(x)):
        print(x[folder]) # print all the foldername inside the folder_path
        folder = +1
    
    0 讨论(0)
  • 2020-11-22 15:43

    Here's my answer using glob without filter if you want to read files with a certain extension in date order (Python 3).

    dataset_path='/mydir/'   
    files = glob.glob(dataset_path+"/morepath/*.extension")   
    files.sort(key=os.path.getmtime)
    
    0 讨论(0)
提交回复
热议问题