Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #94791

Re: [Tutor] Mailbox

Date 2015-07-31 07:53 +1000
From Cameron Simpson <cs@zip.com.au>
Subject Re: [Tutor] Mailbox
References <55ba7488.882c460a.ed373.ffff8098@mx.google.com>
Newsgroups comp.lang.python
Message-ID <mailman.1098.1438293232.3674.python-list@python.org> (permalink)

Show all headers | View raw


On 30Jul2015 19:00, ltc.hotspot@gmail.com <ltc.hotspot@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 <cs@zip.com.au>

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: [Tutor] Mailbox Cameron Simpson <cs@zip.com.au> - 2015-07-31 07:53 +1000

csiph-web