python按修改时间过滤文件

时间:2015-07-14 13:47:11

标签: python logging time

我有以下代码:

def filter_by_time(files):
    print "---List of log files to timecheck: "
    for f in files:
        print f, datetime.datetime.fromtimestamp(os.path.getmtime(f))
    print "------"

    mins = datetime.timedelta(minutes=int(raw_input("Age of log files in minutes? ")))
    print "Taking ", mins, "minutes"
    mins = mins.total_seconds()
    current = time.time()
    difftime = current - mins
    print "current time: ", datetime.datetime.fromtimestamp(current)
    print "logs from after: ", datetime.datetime.fromtimestamp(difftime)   

    for f in files:    
        tLog = os.path.getmtime(f)
        print "checking ", f, datetime.datetime.fromtimestamp(tLog)
        if difftime > tLog:
            print "difftime is bigger than tLog", "removing ", f
            files.remove(f)

    print "*****List of log files after timecheck"
    for f in files:
        print f, datetime.datetime.fromtimestamp(os.path.getmtime(f)) 
    print "******"  
    return files

以及日志文件的样本数量。 输入几分钟时上面代码的输出是:

List of log files to timecheck: 

1copy2.log  11:59:40

1copy3.log  12:13:53

1copy.log  11:59:40

1.log  11:59:40

Age of log files in minutes? 5

Taking  0:05:00 minutes

current time:  2015-07-14 14:02:11.861755

logs from after:  2015-07-14 13:57:11.861755

checking  1 copy 2.log 2015-07-14 11:59:40

difftime is bigger than tLog removing  1copy2.log

checking  1copy.log 2015-07-14 11:59:40

difftime is bigger than tLog removing  1copy.log

List of log files after timecheck



1copy3.log 2015-07-14 12:13:53

1.log 2015-07-14 11:59:40



Collected: 1copy3.log

Collected: 1.log

正如您所看到的,它收集的文件不正确。它做的是检查4个文件,看看是否在最后5分钟内修改了任何文件。它从列表中删除2但应删除4个文件。

(做了一些编辑以便于阅读)

2 个答案:

答案 0 :(得分:2)

在迭代列表时,您将从列表中删除项目。结果是不可预测的。

尝试迭代列表的副本,如下所示:

for f in files[:]:    # Note the [:] after "files"
    tLog = os.path.getmtime(f)
    print "checking ", f, datetime.datetime.fromtimestamp(tLog)
    if difftime > tLog:
        print "difftime is bigger than tLog", "removing ", f
        files.remove(f)

答案 1 :(得分:2)

考虑Python中可用的filter函数。我假设您的输入是一个文件列表,以及您想要检查的过去几分钟,并且您希望根据{{1}之间的时间段内最后修改的文件过滤文件过去和现在的分钟。

min