从目录和子目录中提取文件和时间戳

时间:2013-06-28 19:57:30

标签: python

我有一个工作脚本,它将打印给定目录中的所有文件。我想帮助它再做两件事:

(1)还可以打印每个文件的date_created或时间戳。 (2)上述所有内容不仅适用于给定目录中的文件,也适用于所有子目录中的文件。

这是工作脚本:

from os import listdir
from os.path import isfile, join
from sys import argv

script, filename = argv

mypath = os.getcwd()

allfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

output = open(filename, 'w')

for i in allfiles:
    string = "%s" %i
    output.write(string + "\n")

output.close()

print "Directory printed."

我希望能够打印类似(filename +“,”+ timestamp +“\ n”)或某些替代品。

谢谢!

2 个答案:

答案 0 :(得分:2)

http://docs.python.org/2/library/os.htmlhttp://docs.python.org/2/library/stat.html让你了解。

os.walk将为您提供递归目录行走

stat将为您提供文件时间戳(atime,ctime,mtime)

答案 1 :(得分:1)

此代码段遍历目录+子目录中的文件,并打印出已创建和修改的时间戳。

import os
import time

def walk_files(directory_path):
    # Walk through files in directory_path, including subdirectories
    for root, _, filenames in os.walk(directory_path):
        for filename in filenames:
            file_path   = root + '/' + filename
            created     = os.path.getctime(file_path)
            modified    = os.path.getmtime(file_path)

            # Process stuff for the file here, for example...
            print "File: %s" % file_path
            print "    Created:       %s" % time.ctime(created)
            print "    Last modified: %s" % time.ctime(modified)


walk_files('/path/to/directory/')