modzello86
modzello86

Reputation: 433

Extracting speciific string in Python

I have log file in wich at some point I added timestam creation and now it look like this:
log.txt:

327555
327563
327570
327601
2012-11-19 22:21:37 :: 327001
2012-11-19 22:21:37 :: 327004
2012-11-19 22:21:37 :: 327007
2012-11-19 22:21:37 :: 327008

In my Python script i used to read all lines from log.txt and add it line-by-line to a set for futher usage:

log_file = open('log.txt')
set_log = set([])
for line in log_file:
    set_log.add(line.strip())
log_file.close()

But since timestam was added this solution and gives me wrong values in my set ( it includes timestam as well).

Q: How to make it more flexible, so it udersteads lines without timestams and WITH timestams and extract only proper values?

Upvotes: 0

Views: 43

Answers (1)

Fred Foo
Fred Foo

Reputation: 363627

Just parse away the timestamps. ln.split()[-1] will return the last element after splitting on whitespace, which seems to be what you're after, so

set_log = set(ln.split()[-1] for ln in log_file)

(Using a generator comprehension to replace your loop. The strip() is no longer needed as split() removes all whitespace.)

Upvotes: 2

Related Questions