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