0

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?

1
  • 2
    If you reverse the two methods then you'd get the exact opposite result...
    – Jongware
    May 1, 2016 at 10:09

1 Answer 1

5

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())
1
  • This also worked when I used f.readlines() and then f.read() for two different purposes. In order for it to work, I had to insert a f.seek(0) between the two otherwise the f.read() did not output anything.
    – Glxblt76
    Oct 5, 2023 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.