pythonfilefile-read

Printing file.read() doesn't display file content


I am not being able to understand why file.read() behaves differently when I save it in a variable. Here is the illustration:

with open("file.txt","r") as file:
    content=file.read()
    print(content)
    print("------")
    print(file.read())

And the output is:

a
b

------

So, the last line of the code is not printing anything out.

Anyone care to explain why?


Solution

  • File objects are streams; reading from them advances a file position. Reading again won't reset that file position, and since there was no new data added to the file you get an empty string back.

    Use the file.seek() method if you need to reset the file position to the start:

    file.seek(0)
    print(file.read())