Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a chronological list of files, with the file modification date

I want to create a list of those files in a directory which have the extension .bas, and which were modified after June 1, 2011. Also, I'd like to know how to optionally have the files in the list appear with the date and time the file was last modified, e.g., 'filename.bas 2011-06-04_AM.00.30'

I am a python newbie. I was able to list files having the .bas extension, sorted by date, by using the following code:

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, glob
search_dir = r"e:\test"
files = filter(os.path.isfile, glob.glob(search_dir + "\\*.bas"))
files.sort(key=lambda x: os.path.getmtime(x))

But I can't figure out how to append " date" to the filename in the list.

Any suggestions would be very much appreciated.

like image 580
Marc B. Hankin Avatar asked Oct 11 '22 20:10

Marc B. Hankin


1 Answers

Collect files and dates in a list of tuples and sort that list by the date element. Here is the example code, the comments in it should be sufficient to understand it:

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, glob
search_dir = r"e:\test"
files = filter(os.path.isfile, glob.glob(search_dir + "\\*.bas"))
file_date_tuple_list = []
for x in files:
    d = os.path.getmtime(x)
    #tuple with file and date, add it in a list
    file_date_tuple = (x,d)
    file_date_tuple_list.append(file_date_tuple)
#sort the tuple list by the second element which is the date
file_date_tuple_list.sort(key=lambda x: x[1])

Optionally, you can use a list comprehension to make the code more compact and clean ...

file_date_tuple_list = [(x,os.path.getmtime(x)) for x in files]
file_date_tuple_list.sort(key=lambda x: x[1])

This two lines would replace all the for loop from the first example.

Now if what you want in the list is a string with filename and date formatted then ... add this import ...

from datetime import date

and another line with this list comprehension that takes the modification time stamp and formats it into a string.

file_date_string_list = ["%s %s"%(x[0],date.fromtimestamp(x[1])) \
                                             for x in file_date_tuple_list]

For reversing the order of the sort use the optional parameter reverse in the sort execution:

file_date_tuple_list.sort(key=lambda x: x[1],reverse=True)

For limiting the date to a specific datetime

from datetime import datetime
limit = datetime(2011,01,05,17,0,0) #5pm , Jun 5 2011 
file_date_string_list = ["%s %s"%(x[0],date.fromtimestamp(x[1])) \
                                       for x in file_date_tuple_list \
                                       if datetime.fromtimestamp(x[1]) > limit ]

As you can see you can add an if condition inside the list comprehension, which is really cool.

like image 87
Manuel Salvadores Avatar answered Oct 14 '22 05:10

Manuel Salvadores