0

I've written a simple program to check if something has been written to a file, and if it hasn't then written to the file. Once that is done, I then want to read from the file, but it keeps reading a blank line?

with open("leaderboard.txt", "r+") as infile:
if infile.readline() == "Rank\tName\tTime (secs)":
    print("Already written to.\n")
else:
    print("Writing headers\n")
    infile.write("Rank\tName\tTime (secs)")

contents = infile.read()
print(contents)

The current result I am getting is:

Already written to.

(followed by two blank lines)

Would anyone know the solution to my problem? Thanks!

SOLUTION: Once the file is read once, the file pointer is then positioned at the end of the file. After moving the file pointer back to the beginning I can reread the file. To reposition file pointer use infile.seek(0). See link

Community
  • 1
  • 1
Edwarric
  • 513
  • 2
  • 9
  • 19
  • Is there anything in the file? – Joel Oct 20 '16 at 22:10
  • Briefly: when you do `infile.read()`, there's nothing left to read because you're at the end of the file. – TigerhawkT3 Oct 20 '16 at 22:14
  • Besides, if the goal is to create a header, your code will either add it to an empty file (with no linefeed at the end, note) or add it to the middle of a non-empty file. You should reconsider what sort of input you expect to use, and what result you want to end up with. – TigerhawkT3 Oct 20 '16 at 22:15
  • Yeah, there's "Rank Name Time (secs)" in the file – Edwarric Oct 20 '16 at 22:24
  • Why am I at the end of the file after doing infile.read()? – Edwarric Oct 20 '16 at 22:24
  • 1
    You are at the end of the file _before_ doing that. You read a line, then possible write something, and then there's nothing else in the file. When you try to read the file at that point, it's at the end, so there's nothing left. – TigerhawkT3 Oct 20 '16 at 22:29
  • How would I resolve my issue? So how would I read from the file, from the first line, but still do the first line check thing at the start? – Edwarric Oct 20 '16 at 22:39

0 Answers0