[Tutor] why it is showing attribute error in line7

Steven D'Aprano steve at pearwood.info
Sat Oct 29 05:44:15 EDT 2016


Hello, and welcome!

Please always post the FULL traceback. Python gives you lots of 
information to debug problems, so you don't have to guess, but when you 
throw that information away, we have to guess.

My guess follows below:

On Fri, Oct 28, 2016 at 09:42:35PM -0700, SONU KUMAR wrote:
> fname = raw_input("Enter file name: ")
> if len(fname) < 1 : fname = "mbox-short.txt"
> fh = open(fname)
> count = 0
> for line in fh:
>    line=line.rstrip

That's the problem. You are not calling the method, instead you are 
assigning the method line.rstrip to the variable "line". Watch the 
difference here:

py> line = "some text    "
py> a = line.rstrip()  # with parentheses means call the method
py> b = line.rstrip  # no parens means the method itself
py> print(a)
some text
py> print(b)
<built-in method rstrip of str object at 0xb7aad368>


So using your code, you say:

py> line = line.rstrip  # no parens
py> print(line)
<built-in method rstrip of str object at 0xb7aad368>


which means when you come to the next line of code, you get an error:

>    if not line.startswith("From"):continue

py> line.startswith('From')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 
'startswith'


And look at the error message: it tells you *exactly* what is wrong. You 
have a built-in function or method, not a string.

Always read the full traceback. When you have to ask for help, always 
copy and paste the full traceback.



-- 
Steve


More information about the Tutor mailing list