1

I am writing a class that reads the number of lines in a file before the line "end"

class readFile:

    global count
    global txt

    def __init__(self):
        self.count = 0

    def open(self,file):
        self.txt = open(file,"r")

    def cnt(self):
        str = txt.readline()
        while str != "end":
            self.count += 1
            str = txt.readline()

    def printline(self):
        print "the number of lines = %d" % count

    obj = readFile()
    obj.open(raw_input("which file do you want to read? \n"))
    obj.cnt()
    obj.printline()

But when I run this bit of code i get the following error - NameError: global name 'txt' is not defined

I am shifting from java to python, so if there are any stylistic differences I apologize

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Nike
  • 72
  • 6
  • In this example both `count` and `txt` should be more conveniently be members of your class. Try avoiding globals like herpes. – Hyperboreus Dec 29 '13 at 08:53

4 Answers4

3

You can use global variables in a function other than the one that created them "by declaring it as global in each function that assigns to it."

However, in this case, txt just needs to be a member of the class.

Comments inline below, to help you with your journey from Java to Python...

#!/usr/bin/env python

class ReadFile(object): # Classes have titlecase names and inherit from object
    def __init__(self):
        self.count = 0
        self.txt = None # Initialise the class member here

    def open(self, filename): # file is a Python built-in. Prefer 'filename'
        self.txt = open(filename, "r")

    def cnt(self):
        line = self.txt.readline() # str is a Python built-in. Prefer 'line'.
                                   # Reference the class member with 'self.'
        line = line.strip() # Remove any trailing whitespace
        while line != "end": # TODO: What happens if this line doesn't appear?
            self.count += 1
            line = self.txt.readline().strip()

    def printline(self):
        print "the number of lines = %d" % self.count

obj = ReadFile()
obj.open(raw_input("which file do you want to read? \n").strip())
obj.cnt()
obj.printline()

'''
end
'''
Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

Your txt doesn't need to be a global variable.

In your cnt function, just call it with self.txt. Same remark for your print line function, call count with self.count

Another tip: Don't forget to close your file.

aIKid
  • 26,968
  • 4
  • 39
  • 65
Rudy Bunel
  • 784
  • 1
  • 7
  • 15
1

Just don't use globals.

 class readFile:

        def __init__(self):
            self.count = 0

        def open(self,file):
            self.txt = open(file,"r")

        def cnt(self):
            str = self.txt.readline()
            while str != "end":
                self.count += 1
                str = self.txt.readline()

        def printline(self):
            print "the number of lines = %d" % self.count
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
0

I understand you want to work with classes, but if it's just counting the number of lines in a file, you could also try something like this:

with open('test.py') as f:

    l = [x.strip() for x in f.readlines()]

    try: # assuming 'end' is the only word in the line

        print 'the number of lines = {}'.format(len(l[:l.index('end')]))

    except:

        print 'string "end" not found'
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63