w3resource

Python: Get a directory listing sorted by creation date

Python Basic: Exercise-71 with Solution

Write a Python program to get a directory listing, sorted by creation date.

Sample Solution-1:

Python Code:

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

#Relative or absolute path to the directory
dir_path = sys.argv[1] if len(sys.argv) == 2 else r'.'

#all entries in the directory w/ stats
data = (os.path.join(dir_path, fn) for fn in os.listdir(dir_path))
data = ((os.stat(path), path) for path in data)

# regular files, insert creation date
data = ((stat[ST_CTIME], path)
           for stat, path in data if S_ISREG(stat[ST_MODE]))

for cdate, path in sorted(data):
    print(time.ctime(cdate), os.path.basename(path))
	

Sample Output:

Mon Feb 22 16:11:49 2016 .bash_logout                                                                         
Mon Feb 22 16:11:49 2016 .bashrc                                                                              
Mon Feb 22 16:11:49 2016 .profile                                                                             
Mon May 30 11:45:34 2016 .mysql_history                                                                       
Sat Aug 13 11:37:48 2016 logging_example.out                                                                  
Tue Sep 13 10:56:31 2016 result.txt                                                                           
Tue Sep 20 18:00:14 2016 dddd.txt        
-------
Tue Apr 18 15:06:27 2017 abc.txt                                                                              
Wed Apr 19 13:46:47 2017 .bash_history                                                                        
Wed Apr 19 15:15:52 2017 test.txt                                                                             
Wed Apr 19 16:58:20 2017 4ab8fe20-24f3-11e7-afe4-85767fd0ee52.py  

Flowchart:

Flowchart: Get a directory listing sorted by creation date.

Sample Solution-2:

Python Code:

import os
import time
paths = ["%s %s" % (time.ctime(t),f) for t, f in
sorted([(os.path.getctime(x),x) for x in os.listdir(".")])]
print("Directory listing, sorted by creation date:")
for x in range(len(paths)):
    print(paths[x],)
	

Sample Output:

Directory listing, sorted by creation date:
Mon May 31 13:29:45 2021 main.py 

Flowchart:

Flowchart: Get a directory listing sorted by creation date.

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to sort files by date.
Next: Write a Python program to get the details of math module.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]