8

This is a challenge as well as a question:

I have a folder of data files. I want the following list of lists of information:

Filename:      Created:                     Last modified:

Information = 
[
[datafile1,    Mon Mar 04 10:45:24 2013,    Tue Mar 05 12:05:09 2013],
[datafile2,    Mon Mar 04 11:23:02 2013,    Tue Apr 09 10:57:55 2013],
[datafile2.1,  Mon Mar 04 11:37:21 2013,    Tue Apr 02 15:35:58 2013],
[datafile3,    Mon Mar 04 15:36:13 2013,    Thu Apr 18 15:03:25 2013],
[datafile4,    Mon Mar 11 09:20:08 2013,    Mon May 13 16:30:59 2013]
]

I can sort it myself after I have the Information. Can someone write the function:

def get_information(directory):
    .
    .
    .
    return Information

These posts are useful:

1) How do you get a directory listing sorted by creation date in python?

2) Sorting files by date

3) How to get file creation & modification date/times in Python?

4) Python: sort files by datetime in more details

5) Sorting files by date

6) How do I get the modified date/time of a file in Python?

However: I feel there must exist a better, more re-usable solution which works on windows, and linux.

Community
  • 1
  • 1
  • 1
    http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python?rq=1 –  May 16 '13 at 18:55

1 Answers1

11

I know for a fact that os.stat functions well on both windows and linux.

Documentation here

However, to fit your functionality, you could do:

You can use st_atime to access most recent access and st_ctime for file creation time.

import os,time

def get_information(directory):
    file_list = []
    for i in os.listdir(directory):
        a = os.stat(os.path.join(directory,i))
        file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
    return file_list

print get_information("/")

I'm on a mac and I get this,

[['.dbfseventsd', 'Thu Apr  4 18:39:35 2013', 'Thu Apr  4 18:39:35 2013'], ['.DocumentRevisions-V100', 'Wed May 15 00:00:00 2013', 'Sat Apr 13 18:11:00 2013'],....]
  • YES! Confirmed - this works on windows as well and generates the same output. –  May 16 '13 at 19:47
  • This answer should be known on other threads. We should link to it, or copy it. –  May 16 '13 at 19:58
  • @Doug Sure, be my guest. But any threads that are linked to this question, are simultaneously linked to the respective thread. –  May 16 '13 at 20:05
  • For me both atime and ctime return the created date. My files are in a Windows 8.1 NTFS directory and I'm running Python 2.7 – Logic1 Oct 29 '16 at 01:39