关于datetime:Python:获取目录中所有文件和文件夹的列表,创建时间,上次修改时间。 系统独立的解决方案?

Python: Get a list of all files and folders in a directory, the time of creation, the time of last modification. System independent solution?

这既是一个挑战,也是一个问题:

我有一个数据文件文件夹。
我想要以下信息列表:

1
2
3
4
5
6
7
8
9
10
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]
]

掌握信息后,我可以自己对它进行排序。
有人可以写函数吗:

1
2
3
4
5
def get_information(directory):
    .
    .
    .
    return Information

这些帖子非常有用:

1)如何在python中按创建日期对目录列表进行排序?

2)按日期排序文件

3)如何在Python中获取文件创建和修改日期/时间?

4)Python:按日期时间对文件进行排序,详细信息

5)按日期排序文件

6)如何在Python中获取文件的修改日期/时间?

但是:我觉得必须存在一个更好的,可重用的解决方案,该解决方案可以在Windows和Linux上使用。


我知道os.statwindowslinux上都能很好地工作的事实。

这里的文件

但是,为了适合您的功能,您可以执行以下操作:

您可以使用st_atime访问最新访问,并使用st_ctime获取文件创建时间。

1
2
3
4
5
6
7
8
9
10
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("/")

我在mac上,我明白了,

1
[['.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'],....]