gpt4 book ai didi

python按修改时间过滤文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:39 31 4
gpt4 key购买 nike

我有以下代码:

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 个文件。

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

最佳答案

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

import datetime, os
def files_after (files, min)
lower_time_bound = datetime.datetime.now() - timedelta(minutes=min)
return filter(lambda f: datetime.datetime.fromtimestamp(os.path.getmtime(f)) > lower_time_bound, files)

关于python按修改时间过滤文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408524/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com