If statements only runs the else condition even though the if condition is true

Question:

I’m making a push-up log that requires to see if the text file it generates contains the date, so that it knows to add onto the counting list, or start on a new line with a new date.

I made this dummy search to see if it will work.

from datetime import date

with open("Push-Ups-Log.txt", "a+") as Counter:
    AllLogs = Counter.read()
    if str(date.today()) in AllLogs:
        print("True")
    else:
        print("False")

The text file looks like this:

1. 2022-07-21

Python output:

False

Any reason why?

Asked By: XboxOneSogie720

||

Answers:

When you open a file in 'a+' mode the file pointer is at the end of the file if the file exists. So AllLogs is an empty string.
So you should issue seek method to position file pointer to beginning of the file

from datetime import date

with open("Push-Ups-Log.txt", "a+") as Counter:
    Counter.seek(0)
    AllLogs = Counter.read()
    if str(date.today()) in AllLogs:
        print("True")
    else:
        print("False")


Answered By: Yuri Ginsburg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.