Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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:</p> <pre><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")) 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]) </code></pre> <p>Optionally, you can use a list comprehension to make the code more compact and clean ...</p> <pre><code>file_date_tuple_list = [(x,os.path.getmtime(x)) for x in files] file_date_tuple_list.sort(key=lambda x: x[1]) </code></pre> <p>This two lines would replace all the <code>for</code> loop from the first example.</p> <p>Now if what you want in the list is a string with filename and date formatted then ... add this import ...</p> <pre><code>from datetime import date </code></pre> <p>and another line with this list comprehension that takes the modification time stamp and formats it into a string.</p> <pre><code>file_date_string_list = ["%s %s"%(x[0],date.fromtimestamp(x[1])) \ for x in file_date_tuple_list] </code></pre> <p>For reversing the order of the sort use the optional parameter <code>reverse</code> in the <code>sort</code> execution:</p> <pre><code>file_date_tuple_list.sort(key=lambda x: x[1],reverse=True) </code></pre> <p>For limiting the date to a specific <code>datetime</code></p> <pre><code>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]) &gt; limit ] </code></pre> <p>As you can see you can add an <code>if</code> condition inside the list comprehension, which is really cool.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload