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

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

提交回复
热议问题