16

How to list the files in a directory based on timestamp?

 os.listdir() 

lists in arbitrary order.

Is there a build-in function to list based on timestamp? or by any order?

vkris
  • 2,095
  • 7
  • 22
  • 30

2 Answers2

52

You could call stat() on each of the files and sort by one of the timestamps, perhaps by using a key function that returns a file's timestamp.

import os

def sorted_ls(path):
    mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
    return list(sorted(os.listdir(path), key=mtime))

print(sorted_ls('documents'))
HarryM
  • 1,875
  • 13
  • 7
  • could you explain this as I am not aware of using lambda functions? – vkris Dec 21 '10 at 15:26
  • 6
    Sure, lambdas are basically unnamed functions. They may take arguments before the colon (in this case there is one: f, a filename). The body of a lambda is a single expression, the result of which is used as the lambda's return value. The `sorted` function takes an iterable (such as a list) and returns an iterator than produces a sorted version of the given iterable. Providing a function to the `key` keyword argument allows you to sort by something other than the natural ordering of the items in the given iterable. The `mtime` function is called on each filename and used to sort the list. – HarryM Dec 21 '10 at 15:54
  • That's a nice, clever solution. – jmoz Jul 23 '15 at 11:03
0

My immediate solution is,

 >>> import commands
 >>> a = commands.getstatusoutput("ls -ltr | awk '{print $9}'")
 >>> list  =a[1].split('\n')

As per the duplicate post pointed by bluish, this is a bad solution; why is it bad?

vkris
  • 2,095
  • 7
  • 22
  • 30
  • 4
    this can be done in pure python... no need to shell out and use system utils (which are not cross-platform). also, `subprocess` should be used instead of `commands`. – Corey Goldberg Dec 21 '10 at 15:20