1

I have a simple function that will print text. I call the function the first time, and the text from the file is read. I call it again, but the text is not read.

text = open ("lorem.txt")
def recite():
     print(text.read())

recite() Lorem ipsum dolor sit amet...

recite()

recite()

Sam Andoh
  • 21
  • 1
  • 5
    Try doing `text = open("lorem.txt").read()` and see what happens. (This has no error handling, but it should reveal a bit more about what's going on.) – ChrisGPT was on strike Apr 29 '20 at 13:37
  • Once a file is read completely subsequent reads will have nothing left to read. You can reset the file by doing `text.seek(0)` before reading, but it's better to open the file each time or to cache the contents. – Steven Rumbalski Apr 29 '20 at 13:39
  • Thank you Chris. When I try your suggestion *text* reads the file reliably; – Sam Andoh Apr 29 '20 at 13:48

3 Answers3

3

The read function is a forward-only function. Change your function to the following to get the desired output:

def recite(filepath):
    with open(filepath, "r") as f:
        read_data = f.read()
        print(read_data)
recite('lorem.txt')
recite('lorem.txt')

You could also use the seek function after reading to set the file's current position at the beginning again. Thus, this would be an alternative:

text = open ("lorem.txt")
def recite():
     print(text.read())
     text.seek(0)
recite()
recite()
Code Pope
  • 5,075
  • 8
  • 26
  • 68
1

I believe it works like this. When you open a file, the file pointer is at the beginning. When you read the file, the file pointer iterates through all of the characters in the file and ends up at the end. Thus, calling .read() again has no additional effect. There are a few solutions:

  • Calling file.seek(0) will return the file pointer to the beginning of the file

  • A far better solution is simply to open the file once for each call to recite() or read().

with open("filepath.txt", "r") as file:
     contents = file.read()
DerekG
  • 3,555
  • 1
  • 11
  • 21
-1

You have to close and open it again. It doesn't come back to the beginning of the file automatically.

def recite(filename):
   text = open(filename,'r')
   print (text.read())
   text.close()