0

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

(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") 之类的东西,或者一些替代品。

谢谢!

4

2 回答 2

2

http://docs.python.org/2/library/os.htmlhttp://docs.python.org/2/library/stat.html已经涵盖了。

os.walk 会给你递归目录走

stat 会给你文件时间戳(atime,ctime,mtime)

于 2013-06-28T20:00:24.977 回答
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/')
于 2013-12-29T21:32:45.997 回答