prispvdp
prispvdp

Reputation: 9

How do you split a string into lines with a regular expression in Python?

I have a logfile with 4 lines, for example:

12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)                                      
ERROR message: 1245456487                                                         
The wifi was not available                                                        
The user needs to validate   

Now I want to split the second line from the first line with a regular expression in Python to get:

line1 == '12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)'          
line2 == '2 ERROR message: 1245456487'

Upvotes: 0

Views: 209

Answers (1)

timgeb
timgeb

Reputation: 78690

You can simply split your logfile into a list of lines likes this:

with open('mylogfile.txt') as f:
    lines = list(f)

lines[0] would be the first line, lines[1] the second line, and so on.

Splitting an instance of str into lines can be done like this:

>>> s="""12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x) 
... ERROR message: 1245456487 
... The wifi was not available
... The user needs to validate"""
>>> lines = s.splitlines()
>>> lines[0]
'12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)'
>>> lines[1]
'ERROR message: 1245456487'

You don't need a regular expression for this task in either case.

Upvotes: 1

Related Questions