我正在编写一个类,该类在"结束"行之前读取文件中的行数
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()
但是当我运行这段代码时,我收到以下错误 -名称错误: 未定义全局名称"txt"
我正在从java转向python,所以如果有任何风格差异,我深表歉意
您可以在
创建全局变量的函数之外使用全局变量,"通过在分配给它的每个函数中将其声明为 global
"。
但是,在这种情况下,txt
只需要成为类的成员。
下面内联的评论,以帮助您从Java到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
'''
只是不要使用全局变量。
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
您的txt
不需要是全局变量。
在您的 cnt 函数中,只需使用 self.txt
调用它即可。打印行函数的备注相同,使用 self.count
调用 count
另一个提示:不要忘记关闭文件。
你想使用类,但如果它只是计算文件中的行数,你也可以尝试这样的事情:
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'