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?

查看:1012
本文介绍了Python:获取目录中所有文件和文件夹的列表,创建时间,上次修改时间。系统独立的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个挑战以及一个问题:

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

这些帖子很有用:

1)如何根据创建日期在python中获取目录列表?

2)按日期排序文件

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

4) Python:按日期时间更详细地排序文件

5)按日期排序文件

6 )如何我是否可以在Python中获取修改后的文件的日期/时间?

但是:我觉得必须存在一个更好,更可重复使用的解决方案在windows和linux上。

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

推荐答案

我知道一个事实, os.stat windows linux

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

文档 here

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

However, to fit your functionality, you could do:

您可以使用 st_atime 以访问最近的访问权限,以及 st_ctime 来创建文件创建时间。

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("/")

我在一个 mac ,我得到这个,

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

这篇关于Python:获取目录中所有文件和文件夹的列表,创建时间,上次修改时间。系统独立的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆