python3如何搜索日志文件
因此,对于作业,我必须读取一个日志文件,其中的条目与下面列出的条目相似python3如何搜索日志文件,python,python-3.x,Python,Python 3.x,因此,对于作业,我必须读取一个日志文件,其中的条目与下面列出的条目相似 s12773390 dtremote ::1::1:6 Sat Mar 26 14:03 - 15:08 (01:04) kthao2 dtremote ::1::1:6 Sat Mar 26 11:25 - 11:32 (00:06) jwoodcock dtremote ::1::1:3 Fri Mar 25 23:23 - 23:29
s12773390 dtremote ::1::1:6 Sat Mar 26 14:03 - 15:08 (01:04)
kthao2 dtremote ::1::1:6 Sat Mar 26 11:25 - 11:32 (00:06)
jwoodcock dtremote ::1::1:3 Fri Mar 25 23:23 - 23:29 (00:06)
然后我必须找到一个特定的用户和他们第一次登录的日期。到目前为止,我已经想出了
loginDataFile = open('logindata.dat', 'r')
loginDataList = loginDataFile.readlines()
jwoodcockLogin = [x for x in loginDataList if 'jwoodcock' in x]
print(jwoodcockLogin[len(jwoodcockLogin - 1)])
到目前为止,这让我得到了他们第一次登录的列表元素,但是,我只需要日志条目中的日期,而不是全部内容 如果保证前三个字段没有空格,则可以执行以下操作:
username, type, address, timestamp = jwoodcockLogin[-1].split(None, 3)
print(timestamp)
它将在空格上拆分三次,在第三次空格运行后,将字符串的其余部分作为单个字符串运行
我会注意到,您在这里浪费了大量内存(如果日志文件很大),因为您将整个内容存储在内存中,即使您只关心一行
更简单的解决方案可能是:
lasttimestamp = None
# Use with statement to guarantee the file is closed promptly (on block exit)
with open('logindata.dat') as loginDataFile:
# file objects are lazy iterators of their lines, no need to call
# .readlines() and eagerly slurp the whole thing into (limited) memory
for line in loginDataFile:
# Extract username and timestamp, with _ indicating fields that must
# exist, but we don't care about otherwise
username, _, _, timestamp = line.split(None, 3)
if username == 'jwoodcock':
lasttimestamp = timestamp
if lasttimestamp is not None:
print(lasttimestamp)
else:
print("User not found in log")
它只存储当前正在处理的行和用户看到的最后一个时间戳,因此1 MB日志文件和10 GB日志文件的扫描时间不同,您不会有内存不足的风险。我很想用
grep
和tail
;)的子进程来回答这个问题谢谢你提供的信息,我来试试。@cricket_007,你为什么不这样做呢?只是因为标签表明它必须是Python解决方案?子进程是Python。。。有了grep和tail,循环的东西就消失了,你就有了一行:)。