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

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

    Alex Coventry's answer will produce an exception if the file is a symlink to an unexistent file, the following code corrects that answer:

    import time
    import datetime
    sorted(filter(os.path.isfile, os.listdir('.')), 
        key=lambda p: os.path.exists(p) and os.stat(p).st_mtime or time.mktime(datetime.now().timetuple())
    

    When the file doesn't exist, now() is used, and the symlink will go at the very end of the list.

提交回复
热议问题