Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: [Tutor] Mailbox

16 views
Skip to first unread message

Cameron Simpson

unread,
Jul 30, 2015, 5:54:13 PM7/30/15
to pytho...@python.org
On 30Jul2015 19:00, ltc.h...@gmail.com <ltc.h...@gmail.com> wrote:
>New revision code:
>
>count = 0
>fn = raw_input("Enter file name: ")
>if len(fn) < 1 : fname = "mbox-short.txt"
>for line in fn:
> if 'From' in line.split()[0]: count += 1
>print "There are %d lines starting with From" % count
>print len(line)
>fn = open(fname)
>print "There were", count, "lines in the file with From as the first word"
>
>
>Syntax message produced by iPython interperter:
>
>NameError Traceback (most recent call last)
>C:\Users\vm\Desktop\apps\docs\Python\assinment_8_5_v_2.py in <module>()
> 6 print "There are %d lines starting with From" % count
> 7 print len(line)
>----> 8 fn = open(fname)
> 9 print "There were", count, "lines in the file with From as the first wor
>d"
>
>NameError: name 'fname' is not defined

I have reposted this to the python-list. Please always reply to the list.

The message above is not a syntax error. It is a NameError, which happens at
runtime.

It is complaining that the name "fname" is not defined.

This is because you have the names "fn" and "fname" confused in your code.
Based on your code, "fname" is supposed to be the filename (a string) and "fn"
is meant to be the open file object (a file), since you have this line:

fn = open(fname)

However, you set "fn" from raw_input when you should set "fname". You also have
the open() call _after_ your loop, but the loop needs to read from the open
file, so these things are out of order.

Cheers,
Cameron Simpson <c...@zip.com.au>
0 new messages