每次的Python类方法输出都不同

假设我有一个名为“ text.txt”的文本文件,其中包含:

Apple
Orange
Strawberry

共3行,我有一节课:

class ReadTextFile:
  def __init__(self, filename):
    self.filename = (open(filename, 'r'))

  def number_of_lines(self):
    num = 0

    for line in self.filename:
      line = line.strip("\n")
      num += 1

    return(num)

当我使用该类计算行的总数时,在第一次尝试时,它给我的正确答案是“ 3”,但在此之后它给了我“ 0”,除非我重新定义了变量“ text”:

>>> text = ReadTextFile('text.txt')
>>> text.number_of_lines()
3
>>> text.number_of_lines()
0
>>> text.number_of_lines()
0
...
>>> text = ReadTextFile('text.txt')
>>> text.number_of_lines()
3
>>> text.number_of_lines()
0
...

我在这里做错了什么?

评论
  • kalias
    kalias 回复

    Use self.filename.seek(0) to reset the file reader pointer.

    Read: Why can't I call read() twice on an open file?

  • 未语人先羞
    未语人先羞 回复

    尝试这个:

    class ReadTextFile:
      def __init__(self, filename):
        self.filename = filename
    
      def number_of_lines(self):
        num = 0
    
        with open(self.filename, 'r') as file:
            for line in file:
              line = line.strip("\n")
              num += 1
    
        return(num)
    
    text = ReadTextFile('txt.txt')
    print(text.number_of_lines())
    print(text.number_of_lines())
    print(text.number_of_lines())