1

I have written a little class which reads a text file and which have a method for printing the text (file.output()). For the first call it worked, but the second call of the method nothing is happening. I do not understand why, since I assume that the FOR-Loop does not change anything.

class Datei():
    def __init__(self, filename):
        self.fileobject = open(filename)
        
    def output(self): 
        for line in self.fileobject: 
            print(line.rstrip())
        
    
    def end(self): 
        self.fileobject.close()

file = Datei("yellow_snow.txt")
file.output()
print("second try")
file.output()

file.end()

I expected the text of the text file to be printed twice, but it is only printed once.

Dirk
  • 21
  • 3

1 Answers1

6

When you read a file, you move a pointer through it, and it's now at the end - you can .seek(0) to get back to the start (or other positions, 0 is where you started from, which is the beginning if you're not in append mode)

with open(path) as fh:
    print(fh.tell())  # start of file
    print(fh.read())  # get everything and display it
    print(fh.tell())  # end of file
    fh.seek(0)        # go back to the beginning
    print(fh.tell())  # start of file
    print(fh.read())

More detail in Python Documentation 7.2.1. Methods of File Objects

ti7
  • 16,375
  • 6
  • 40
  • 68