Python Error: TypeError: the 'int' object is not callable

advertisements

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:'.

Link for mbox-short.txt file: http://www.pythonlearn.com/code/mbox-short.txt

fopen = raw_input('Enter the file name you want to open: ')
fname = open(fopen)
line = 0
count = 0
pieces = 0
email = list()
for line in fname:
    lines = line.rstrip()
    if not line.startswith('From '):
        continue
    pieces = line.split()
    print pieces[1]
print 'There were' ,count(pieces[1]), 'lines in the file with From as the first word

I managed to get the correct output, until the last print message.

Execution:

Enter the file name you want to open: mbox-short.txt

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Traceback (most recent call last):
print 'There were' ,count(pieces[1]), 'lines in the file with From as   the first word'

TypeError: 'int' object is not callable

I am not sure why I am getting this Traceback.


As the comments in the question have mentioned, count is not listed as a function - instead, it's an int. You can't pass pieces[1] to it and expect it to magically increment itself.

If you really want the counts this way, simply update the count while looping through the file.

fopen = raw_input('Enter the file name you want to open: ')
fname = open(fopen)
line = 0 # unnecessary
count = 0
pieces = 0 # also unnecessary
email = list() # also unnecessary
for line in fname:
    lines = line.rstrip()
    if not line.startswith('From '):
        continue
    pieces = line.split()
    print pieces[1]
    count = count + 1 # increment here - counts number of lines in file
print 'There were', count, 'lines in the file with From as the first word