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

Time:07-22

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?

CodePudding user response:

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")


  • Related