Thursday, February 9, 2017

Parsing Lines

When we are reading a file we want to do some manipulation with the lines in a file other than just reading the file. Often we search for specific information in a file and then parse the line to find some interesting part of the file. What if we wanted to print out the day of the week from those lines that start with “From”.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
The split method is very effective in this case and we can use it to split the line in words and collect the word Sat.

>>> t = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> words = t.split()
>>> print words
['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
>>> print words[2]
Sat

No comments:

Post a Comment