因此,对于分配,我必须阅读一个日志文件,该文件具有类似于下面列出的条目。
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)
将在第三个字符串以单字符串运行之后将其余的字符串在Whitespace上拆分。
。我会注意到,您在这里浪费大量内存(如果日志文件很大(,因为您将整个内容存储在内存中,即使您只关心一行。
一个简单的解决方案可能是:
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日志文件仅在扫描时间上有所不同,您不会冒险使用存储器的风险。