4

I using python 2.7 in ubuntu. How do i sort files in more detail order because i had a script that create into numbers of txt flies for split seconds. I had mod a script, it can find the oldest and youngest file but it seem like it just compare with the second but not milliseconds.

My print output:

output_04.txt                     06/08/12 12:00:18
output_05.txt                     06/08/12 12:00:18

-----------
oldest: output_05.txt    
youngest: output_05.txt
-----------

But the right order of oldest file should be "output_04.txt". Any expertise know? Thanks!

Updated: Thanks everyone. I did try out with all of the codes but seem like can't have the output i need. Sorry guys, i did appreciated you all. But the example of my files like above have the same time, so if the full-date, hour, min, sec are all the same, it have to compare by millisecond. isn't it? Correct me if im wrong. Thanks everyone! Cheers!

leong
  • 339
  • 3
  • 5
  • 12
  • 1
    Is it possible that access information is only store with a resolution of seconds, not milliseconds? – Joel Cornett Jun 08 '12 at 06:23
  • related: http://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python – jfs Jun 08 '12 at 08:28

4 Answers4

4

You can use os.path.getmtime(path_to_file) to get the modification time of the file.

One way of ordering the list of files is to create a list of them with os.listdir and get the modification time of each one. You would have a list of tuples and you could order it by the second element of the tuple (which would be the modification time).

You also can check the resolution of os.path.getmtime with os.stat_float_times(). If the latter returns True then os.path.getmtime returns a float (this indicates you have more resolution than seconds).

Diego Navarro
  • 9,316
  • 3
  • 26
  • 33
2
def get_files(path):
    import os
    if os.path.exists(path):
        os.chdir(path)
        files = (os.listdir(path))
        items = {}
        def get_file_details(f):
            return {f:os.path.getmtime(f)}
        results = [get_file_details(f) for f in files]
        for result in results:
            for key, value in result.items():
                items[key] = value
    return items

v = sorted(get_files(path), key=r.get)

get_files takes path as an argument and if path exists, changes current directory to the path and list of files are generated. get_file_details yields last modified time for the file.

get_files returns a dict with filename as key, modified time as value. Then standard sorted is used for sorting the values. reverse parameter can be passed to sort ascending or descending.

Kracekumar
  • 19,457
  • 10
  • 47
  • 56
2

You can't compare the milliseconds because there is no such information.

The stat(2) call returns three time_t fields: - access time - creation time - last modification time

time_t is an integer representing the number of seconds (not of milliseconds) elapsed since 00:00, Jan 1 1970 UTC.

So the maximum detail you can have in file time is seconds. I don't know if some filesystem provides more resolution but you'd have to use specific calls in C and then write wrappers in Python to use them.

LtWorf
  • 7,286
  • 6
  • 31
  • 45
1

HI try following code

# 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
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)

Hope this will help

Thank You

ifixthat
  • 6,137
  • 5
  • 25
  • 42