0

I have a variable that reads values from a file. It doesn't return empty when I just print the variable, but it returns empty when I print the variable and other words. This is really weird.

My code:

f = open(file, "r")
print("f.read(): " + f.read()) // Successfully returns the text in the file
print('"ABC" + f.read() + "ABC": ' + "ABC" + f.read() + "ABC") // Unexpected return ""ABC" + f.read() + "ABC": ABCABC"

Why is there such a strange thing? How to solve this problem? I would appreciate any help. Thank you in advance!

My Car
  • 4,198
  • 5
  • 17
  • 50
  • 1
    after you call `f.read()` the first time, it reads the whole file. Unless you close and reopen the file or seek back to the beginning, the next `f.read()` returns nothing because you're at the end of the file. – Mark Tolonen Oct 30 '22 at 01:19
  • 1
    The first time you call it, `f.read()` reads the entire file. The next time you call it the file is at `EOF` so it returns an empty string. You should either assign it to a variable when you call it the first time, or rewind the file if you want to read it again. – craigb Oct 30 '22 at 01:19

0 Answers0