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


Groups > comp.lang.python > #94791 > unrolled thread

Re: [Tutor] Mailbox

Started byCameron Simpson <cs@zip.com.au>
First post2015-07-31 07:53 +1000
Last post2015-07-31 07:53 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#94791 — Re: [Tutor] Mailbox

FromCameron Simpson <cs@zip.com.au>
Date2015-07-31 07:53 +1000
SubjectRe: [Tutor] Mailbox
Message-ID<mailman.1098.1438293232.3674.python-list@python.org>
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>

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web