Search code examples
python-2.7if-statementfor-loopcountcontinue

Python : count function does not work


I am stuck on an exercise from a Coursera Python course, this is the question:

"Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: From [email protected] Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'. You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt"

Here is my code:

fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
    words = line.split()
    if len(words) > 2 and words[0] == 'From':
        print words[1]
        count = count + 1
    else:
        continue        
print "There were", count, "lines in the file with From as the first word"`

The output should be a list of emails and the sum of them, but it doesn't work and I don't know why: actually the output is "There were 0 lines in the file with From as the first word"


Solution

  • I used your code and downloaded the file from the link. And I am getting this output:

    There were 27 lines in the file with From as the first word

    Have you checked if you are downloading the file in the same location as the code file.