0

我正在尝试编写代码来获取在特定日期范围内创建/修改的目录中的文件。

我对 linux 了解不多,我想知道我可以使用什么命令来获取在我指定的日期范围内匹配的目录中的文件列表。

此外,这种查询的正确格式是什么,因为这个过程将是自动化的,用户只需输入他的开始和结束日期。

到目前为止的相关代码:

#! /usr/bin/env python

import os
import copy
import subprocess
import optparse

def command(command):
    env = copy.deepcopy(os.environ)
    proc = subprocess.Popen([command],
                shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    result = proc.stdout.read()

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option("-s", "--startdate", dest = "startdate",\
                      help = "the starting date of the files to search")
    parser.add_option("-e", "--enddate", dest = "enddate",\
                      help = "the ending date of the files to search")
    (options, args) = parser.parse_args()

    # commands
    file_names = command("get files that match dates command")

我必须在该命令中输入什么来获取这些文件名?

编辑:

相反 - 它不一定是命令,如果它可以使用纯代码完成,os.walk例如,那也很棒。我知道某些功能在 Linux 和 Windows 中不能完全正常工作,因此需要在这件事上提供帮助。

编辑2:

无论采用哪种方法,用户都应输入两个日期:开始和结束。然后获取在这些日期之间修改/创建的所有文件。

4

1 回答 1

2

一种选择是在行中使用某些内容os.walk并根据 ctime/mtime 过滤掉文件,您可以像这样得到:

import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))

如果您更喜欢使用 shell,那么find您的朋友就是这样,带有以下标志:

-ctime n 文件状态最后一次更改是 n*24 小时前。

-mtime n 文件的数据最后一次修改是在 n*24 小时前。

[编辑]

一个小代码示例,用于获取给定目录(“。”)中文件的修改时间:

import os
from os.path import join
import datetime


def modification_date(filename):
        t = os.path.getmtime(filename)
        return t

def creation_date(filename):
        t = os.path.getctime(filename)
        return t

for root, dirs, files in os.walk("."):
        for name in files:
        print join(root, name), modification_date(join(root, name)), creation_date(join(root, name))

根据您特定的命令行参数实现,您希望将命令行上传递的内容转换为 unix 时间戳并与任一日期进行比较。

于 2012-08-08T15:45:12.223 回答