1

what i am trying to do is get a returning value from abcd method, and use this value to as a the substitue of fname and the error is continues to occur.

how can i fix this error?

ICB164000395.txt has four lines. and i want line_count print out 4(The number of lines in the text file)

class Test():
    def abcd(self):
        self.a = a
        a = 'ICB164000395.txt'
        return a


    def line_count(self, fname):
        with open(fname) as f:
            for i, l in enumerate(f):
                pass
        return i + 1
        print(i + 1)

t = Test()
t.line_count(abcd())

and the error appears like this

Traceback (most recent call last): File "C:\Users\mg\Desktop\Tubuc\openAPI\test9.py", line 16, in t.line_count(abcd(fname)) NameError: name 'abcd' is not defined

2
  • 4
    What is the error? Please include the full traceback in the question. Commented Aug 9, 2018 at 13:16
  • 1
    You're not providing a full file path so I assume the "error" is to do with not knowing where to look for your file. Commented Aug 9, 2018 at 13:17

3 Answers 3

1

Just looking at the function:

def abcd(self):
    self.a = a
    a = 'ICB164000395.txt'
    return a

I'm guessign you're getting an error at self.a = a .. Because a is not defined yet. It's not passed in either.

I think what you want is:

class Test():
    def abcd(self):
        a = 'ICB164000395.txt' # you'll need to correct the path to this file
        return a


    def line_count(self, fname):
        with open(fname) as f:
            for i, l in enumerate(f):
                pass
        return i + 1
        print(i + 1)

t = Test()
t.line_count(t.abcd())
Sign up to request clarification or add additional context in comments.

Comments

0

abcd is an instance method so you have to call it from an instance of your class

t = Test()
t.line_cont(t.abcd())

Your abcd method also uses the variable a before it is ever defined, so you could change it to

def abcd(self):
    self.a = 'ICB164000395.txt'
    return self.a

Comments

0

It appears what you want from your abcd method is typically handled in an init. You can set the file name when you instantiate a Test object. Then you can call the line count. Your line_count method should also specify how you are opening the file 'r' for read mode.

class Test():
    def __init__(self, file_name):
        self._file_name = file_name


    def line_count(self):
        with open(self._file_name, 'r') as f:
            for i, l in enumerate(f):
                pass
        return i + 1
        print(i + 1)

t = Test('ICB164000395.txt')
t.line_count()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.