cs at zip.com.au
Thu Jul 30 23:53:35 CEST 2015
On 30Jul2015 19:00, ltc.hotspot at gmail.com <ltc.hotspot at 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(): count += 1
>print "There are %d lines starting with From" % count
>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
>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
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.
Cameron Simpson <cs at zip.com.au>
More information about the Python-list