2

I have a program, in which I need to load a string from inside a text file to a variable. It looks something like this (I have code that makes sure the file in the given path exists prior to this):

file = open("path to the file", "r")
if file.read() != "":
    msg = file.read()
    print("String is not empty, here's what it said: " + file.read() + ", here's what was saved: " + msg)

When I run the code, it returns this:

String is not empty, here's what is said: , here's what was saved: 

When I open the text file, I can clearly see its content isn't empty, it's a normal string of text. That means that for some reason, the read() function fails to read the string that is clearly there. I have done all the bug searching I could've with my level of skill, made sure all my paths and stuff are correct and there aren't any typos, and searched through many stack overflow posts, none of which contained a solution to my problem. What could be causing this problem? If I failed to mention an important part of my code, please ask me for it.

Mymokol
  • 61
  • 7
  • 2
    The first time you run file.read(), the cursor already goes to the end of the file. With a given file object you can only call read once (due to how it works in C) – DownloadPizza Apr 25 '21 at 09:52
  • @DownloadPizza is right. Also, you are trying to read the file twice. User with open() as instead. – tino Apr 25 '21 at 09:57

1 Answers1

4

The first call to read already consumes the whole string and throws it away, as it is only used in the if-statement. Only call file.read() once and save the string to a variable:

file = open("path to the file", "r")
s = file.read()
if s != "":
    print("String is not empty, here's what it said: " + s)
xjcl
  • 12,848
  • 6
  • 67
  • 89
  • Thanks, I've already solved the problem with help from the commentors, I used file.seek(0) before the second read() and it works just fine. – Mymokol Apr 25 '21 at 10:36