Home > Back-end >  (Python) Check Word Count in a File and then congratulate you if you've hit a certain Number of
(Python) Check Word Count in a File and then congratulate you if you've hit a certain Number of

Time:07-23

I tried writing something where Python checks a file's number of words yesterday and the file's words today. Then it compares the values of both with each other and gives you a message according to how much you wrote since yesterday.

But it seems to save the same word count value in both yesterday and today.

import datetime

today = datetime.date.today()
yesterday = datetime.date.today()   datetime.timedelta(days=-1)

if yesterday:
    file = open("python_test.txt", "r")
    read_data = file.read()
    per_word = read_data.split()
    y = len(per_word)
    if today:
        file = open("python_test.txt", "r")
        read_data = file.read()
        per_word = read_data.split()
        x = len(per_word)
        if x > y:
            print("Good job! You wrote a lot!")
        else:
            print("You should try to keep up!")

Any idea on how to fix that or how to optimize the code?

CodePudding user response:

Because yesterday and today are dates, they always are True with if statement. And you read same text file for yesterday and today so your code ran wrong. Try this

import datetime

today = datetime.date.today()
yesterday = datetime.date.today()   datetime.timedelta(days=-1)

try: # check if file exists
    with open(f"data_{yesterday}.txt", "r") as read_yesterday: # data_2022-07-22.txt file
        yesterday_data = read_yesterday.read()
        per_word = yesterday_data.split()
        yesterday_count = len(per_word)
except:
    yesterday_count = 0

try: # check if file exists
    with open(f"data_{today}.txt", "r") as read_today: # data_2022-07-23.txt file
        today_data = read_today.read()
        per_word = today_data.split()
        today_count = len(per_word)
except:
    today_count = 0
    
if today_count > yesterday_count:
    print("Good job! You wrote a lot!")
else:
    print("You should try to keep up!")
  • Related