Python - 按日期过滤

时间:2010-03-20 16:32:05

标签: python login

如何计算在Python中使用日志文件的系统每天完成的登录次数?

2 个答案:

答案 0 :(得分:1)

你不需要Python,shell会这样做:

grep "Login succeeded_or_whatever_the_log_says" logfile | wc -l

如果您真的坚持使用Python,请尝试

print(sum(
     1 for line in open('logfile')
           if 'Login succeeded_or_whatever_the_log_says' in line))

如果登录suceeded消息跨越多行:

print(open('logfile').read().count('login\nsucceeded'))

您无需担心关闭文件句柄;在GC文件句柄时,Python会自动执行此操作:

$ touch x
$ python -c 'import time; open("x"); time.sleep(2)' & sleep 1 && fuser x
[1] 23232
$

$ python -c 'import time; f=open("x"); time.sleep(2)' & sleep 1 && fuser x
[1] 23265
x:                   23265
$

答案 1 :(得分:-1)

您可以使用day作为键创建字典,并将登录计数作为值。 然后逐行读取文件,从每行提取日期并增加当天的登录计数。

我认为这样的事情应该有效:

login_cnts = {}

def get_date(line):
    """extract date from line, in this example line starts with YYYY-MM-DD (10 chars)"""
    if line and len(line) > 10:
        return line[:10]
    return None


for line in open(fname):
    date_str = get_date(line)
    if date_str:
        try:
            login_cnts[date_str] += 1
        except KeyError:
            login_cnts[date_str] = 1

days = login_cnts.keys()
days.sort()
for d in days:
    print("%s: %d" % (d, login_cnts[d]))