2018年1月9日 星期二

Python: Get a directory listing sorted by creation date

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:-
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))

=========== RESTART: F:/Python_APSC/py-ex-basic-71.py ===========
Fri Dec 22 22:43:10 2017 a017-2.py
Fri Dec 22 23:06:00 2017 a017-3.py
Fri Dec 22 23:29:57 2017 a017-4.py
Sat Dec 23 09:15:20 2017 a020.py
Sat Dec 23 11:59:38 2017 a021-1.py
Sat Dec 23 12:02:48 2017 a021-2.py
Sat Dec 23 12:07:37 2017 a021-3.py
Sat Dec 23 12:16:55 2017 a021-4.py
Sat Dec 23 12:32:30 2017 a022.py
Sat Dec 23 12:41:51 2017 a022-1.py
Sat Dec 23 13:02:07 2017 a024.py
Sat Dec 23 13:31:26 2017 a07.py
Sat Dec 23 13:51:08 2017 a08.py
Sat Dec 23 13:56:43 2017 a11.py
Sat Dec 23 14:02:14 2017 a012.py
Sat Dec 23 14:08:32 2017 a014.py
>>> 

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...