willemdh
willemdh

Reputation: 856

Python filtered and date sorted list

How would I have to create a date modified sorted list with Python of all files in /var/log starting with yum.log

ls -la /var/log/yum.log*                                                                                                      [17-01-04 11:36:41]
-rw-------. 1 root root     0 Jan  1 03:45 /var/log/yum.log
-rw-------. 1 root root 16062 Jan 13  2016 /var/log/yum.log-20160113
-rw-------. 1 root root 36020 Dec 22 16:28 /var/log/yum.log-20170101

This code creates the list, but it is sorted by name.

logdir = '/var/log'
yum_logs = sorted([f for f in os.listdir(logdir) if f.startswith('yum.log')])

How can I sort this list by date modified so the newest yum logfile comes first?

Upvotes: 0

Views: 79

Answers (2)

ettanany
ettanany

Reputation: 19806

You can use os.path.getmtime():

logdir = '/var/log'
yum_logs = [f for f in os.listdir(logdir) if f.startswith('yum.log')]
sorted(yum_logs, key=lambda f: os.path.getmtime(os.path.join(logdir, f)))

You can pass reverse=True to sorted to reverse the order:

sorted(yum_logs, key=lambda f: os.path.getmtime(os.path.join(logdir, f)), reverse=True)

Upvotes: 1

Maurice Meyer
Maurice Meyer

Reputation: 18106

You get modification time using os.stat:

logdir = '/var/log'
files = [f for f in os.listdir(logdir) if f.startswith('yum.log')]
files.sort(key=lambda x: os.stat(os.path.join(logdir, x)).st_mtime)

Upvotes: 2

Related Questions