python按修改的时间过滤文件 [英] python filter files by modified time
本文介绍了python按修改的时间过滤文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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
以及一些示例日志文件.输入几分钟后,以上代码的输出为:
And a sample number of log files. The output of the above code when I enter a few minutes is:
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个文件.
As you can see the files it has collected are not correct. What its doing is checking the 4 files to see if any were modified in the last 5 mins. It removes 2 from the list but should have removed the 4 files.
(进行一些编辑以使其更易于阅读)
(Made some edits to make easier to read)
推荐答案
在迭代列表时,您将从列表中删除项目.结果是不可预测的.
You are removing items from the list while you are iterating the list. The result is unpredictable.
尝试遍历列表的副本,如下所示:
Try iterating over a copy of the list like so:
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)
这篇关于python按修改的时间过滤文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文