Reputation: 72
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
Upvotes: 1
Views: 168
Reputation: 7009
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'
Upvotes: 0
Reputation: 141928
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
'''
Upvotes: 3
Reputation: 794
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.
Upvotes: 1
Reputation: 32449
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
Upvotes: 1