Sunday 25 January 2015

Python - Extract lines from text file starting with From

Source file:

Let's assume text file containing bunch of lines while some of them start with "From". As an example such a line can look like following:

From louis@media.berkeley.edu Fri Jan  4 18:10:48 2008

What we are trying to do is to parse all the lines from the source file starting with "From" and have them written line by line as a list and at the end count number of lines matching our criteria.


Python code is then as per following:

fname = raw_input("Enter file location: ")
# source file, e.g. C:\Python34\Doc\SourceFile.txt
fh = open(fname)
count = 0
lst = list()
for line in fh:
    line = line.rstrip("\n")
    if line.startswith("From "):
        count = count + 1
        lst.append(line.split())
#
# Define initial item in a list
i = 1
for i in lst:
    # print second item in each list
    print i[1]
#
print "There were", count, "lines in the file with From as the first word"


Example of results:

stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
rjlowe@iupui.edu
zqian@umich.edu

rjlowe@iupui.edu
...
There were 15 lines in the file with From as the first word

No comments:

Post a Comment