File List by Date (Python)

vegaseat 2 Tallied Votes 8K Views Share

This code snippet allows you to list the files in a folder sorted by "last modified date". The tuple returned by the os.stat() function contains amongst other things the last modified date, which is then converted by the time.localtime() function to a tuple that is ideal for sorting. You can select the folder and the type of file you want to display.

Lardmeister commented: practical code +10
# retrieve the file information from a selected folder
# sort the files by last modified date/time and display in order newest file first
# tested with Python24    vegaseat    21jan2006

import os, glob, time

# use a folder you have ...
root = 'D:\\Zz1\\Cartoons\\' # one specific folder
#root = 'D:\\Zz1\\*'          # all the subfolders too

print '-'*60  # just vanity

date_file_list = []
for folder in glob.glob(root):
    print "folder =", folder
    # select the type of file, for instance *.jpg or all files *.*
    for file in glob.glob(folder + '/*.*'):
        # retrieves the stats for the current file as a tuple
        # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
        # the tuple element mtime at index 8 is the last-modified-date
        stats = os.stat(file)
        # create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59),
        # weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch
        # note:  this tuple can be sorted properly by date and time
        lastmod_date = time.localtime(stats[8])
        #print image_file, lastmod_date   # test
        # create list of tuples ready for sorting by date
        date_file_tuple = lastmod_date, file
        date_file_list.append(date_file_tuple)
    
#print date_file_list  # test

date_file_list.sort()
date_file_list.reverse()  # newest mod date now first

print "%-40s %s" % ("filename:", "last modified:")
for file in date_file_list:
    # extract just the filename
    folder, file_name = os.path.split(file[1])
    # convert date tuple to MM/DD/YYYY HH:MM:SS format
    file_date = time.strftime("%m/%d/%y %H:%M:%S", file[0])
    print "%-40s %s" % (file_name, file_date)
manouch 0 Newbie Poster

where is your code ? :cry:

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Looks like someone ate it! I reloaded the submission.
Good thing I checked the comments! Thanks ...

rmatelot 0 Newbie Poster

good stuff thanks

danholding 5 Junior Poster in Training

hi I am doing something very similar what i want is to be able to pull the 6 latest modified / original file like so ...
ex1.txt = 28/06/10
ex2.txt = 27/06/10
ex3.txt = 24/06/10
ex4.txt = 19/06/10

I am using the same code as above with a few tweaks for other operations i need to do in this program

at the moment i get the 6 latest files but some of them have the same date i need to get the latest files but only 1 per date
this is what i get atm
ex1.txt = 28/06/10
ex2.txt = 28/06/10
ex3.txt = 28/06/10
ex4.txt = 17/06/10
ex5.txt = 17/06/10
ex6.txt = 16/06/10

Tensigh 5 Newbie Poster

This code ROCKS, it's exactly what I was looking for.

By any chance, is there a way to add a count of files by file date? That is, if I have 10 files created Dec 1, and 25 files created Dec 3, how could I add that?

Either way, glad you put this out there. Thanks again!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can add this code to the end of the snippet code ...

print('-'*60)

# optional, count files with matching dates
date_name_list = []
for file in date_file_list:
    # extract just the filename
    folder, file_name = os.path.split(file[1])
    # convert date tuple to MM/DD/YYYY date format
    file_date = time.strftime("%m/%d/%y", file[0])
    date_name_list.append((file_date, file_name))

# contains date:count pairs
date_count_dict = {}
# contains date:[files] pairs
date_name_dict = {}
for date, name in date_name_list:
    # word_freq[word] = word_freq.get(word, 0) + 1
    date_count_dict[date] = date_count_dict.get(date, 0) +1
    date_name_dict.setdefault(date, []).append(name)

import pprint
print("Files with the same date:")
pprint.pprint(date_name_dict)
print('-'*60)
print("Same dates count:")
pprint.pprint(date_count_dict)
dcampbell 0 Newbie Poster

Thanks for this! It has helped me quite a bit.

lockdon 0 Newbie Poster

New to coding and python, I came across your script and wanted to use a slightly modified form ofit. I need to get only partial filenames. I have a set delimiter that I am able to use as a "drop from here" point and want to modifiy the output to use the shortened string. I assume I can use something along the lines of,

line.split(".") [0]

But I am not sure how to use it in this case. I am guessint that it would need to be somewhere in the for loop starting at line 37. Any help would be appreciated

ihatehippies 11 Junior Poster

if you want to drop everything after the last "." you would add this after line 39

file_name = ".".join(file_name.split(".")[:-1])

Here is a breakdown of that code

file_name = "test.file.txt"

file_name.split(".")
<<< ["test", "file", "txt"]

take a slice of that minus the last item in the list

["test", "file", "txt"][:-1]
<<< ["test", "file"]

then reinsert the remaining periods that were 'split' in step 1 with 'join'

".".join(["test", "file"])
<<<"test.file"

if you are wanting only the first part file_name then the code would be

file_name = file_name.split(".")[0]
like you posted above

lockdon 0 Newbie Poster

Sweet, file_name = file_name.split(".")[0] did exactly what I needed. Now that I have the formatI need it is on th the next step. Thanks ihatehippies for that clarification and thanks to vegaseat for throwing this up.
Hopefully I will have the full modified version to add (with notes) by the end of the day today.

leong87 0 Newbie Poster

anyone know how to mod this code to something like:
after the list has sorted, it can call the oldest file and try excute something like send this file to an email.
and also after which del the file.
Would be appreciated if any expertise will help. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.