0

每次生成新文件时,都会在一个目录中生成一些日志文件。

我的目的是获取 10 分钟内生成的大量文件。要实时获得这样的值。数据如下:

00:00 ~ 00:10        10 files

00:10 ~ 00:20        23 files

...

23:50 ~ 23:59        12 files

所以我的想法是在 Linux 系统上通过 crontab 任务每 10 分钟运行一次统计脚本。逻辑第一次运行脚本:通过 . 获取当前文件列表glob.glob("*")

让我说A,所以当脚本下次运行时(10分钟后),它将glob再次运行以获取当前文件列表B。我需要B中的不同值。没有A。所以我可以获得数量。怎么做?如果你有其他好的方法,请分享。

4

2 回答 2

3

你想看看set。您可以执行以下操作:

setA = set(listA)
setB = set(listB)
new_list = list(setB - setA)

您还可以执行其他设置逻辑来识别已删除的文件等。

于 2012-11-16T16:31:51.023 回答
0

正如我对@tcaswell 的回答所评论的那样,使用 Python 的内置 set 类是解决此类问题的绝佳方法。下面是一些基于 Tim Golden 的 Python Stuff 文章Watch a Directory for Changes的示例代码:

import os

firstime = False
path_to_watch = '.'

try:
    with open('filelist.txt', 'rt') as filelist:
        before = set(line.strip() for line in filelist)
except IOError:
    before = set(os.listdir(path_to_watch))
    firstime = True

if firstime:
    after = before
else:
    after = set(os.listdir(path_to_watch))
    added = after-before
    removed = before-after
    if added:
        print 'Added: ', ', '.join(added)
    if removed:
        print 'Removed: ', ', '.join(removed)

# replace/create filelist
with open('filelist.txt', 'wt') as filelist:
    filelist.write('\n'.join(after) + '\n')
于 2012-11-16T17:58:19.313 回答