When one condition is satisfied, I don’t want the other if condition to be conducted (python)


    def creation_time_of_files(folder_path, selected_date):
        
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            # print(file_path)

            if os.path.isfile(file_path) and filename.endswith(".txt"):
                creation_time = os.path.getctime(file_path)
                formatted_time = datetime.fromtimestamp(
                    creation_time).strftime("%Y-%m-%d")
                
                if selected_date==date.today().strftime("%Y-%m-%d"):
                    if formatted_time==selected_date: 
                     with open(file_path, 'r') as file: #when there's today's diary
                        content = file.read()
                        file_window = tk.Toplevel(new_window2)
                        lab = tk.Label(file_window, text=str(content))
                        lab.pack()
                        
                    elif formatted_time!=selected_date: #there's no today's diary
                        
                        real_diarypage()
                 
                if selected_date!=date.today().strftime("%Y-%m-%d") and formatted_time==selected_date:
                    with open(file_path, 'r') as file:
                        content = file.read()
                        file_window = tk.Toplevel(new_window2)
                        
                        lab = tk.Label(file_window, text=str(content))
                        lab.pack()
                        return content


So a file will go through the condition “if formatted_time==selected_date”, and then it’ll go out of the whole if loop. Then, another file, which is written before today, will go through the condition “elif formatted_time!=selected_date” and real_diarypage() will be done. real_diarypage() is a function of writing a new diary.

I want today’s diary pops up when I click the calendar. However, although when there’s today’s diary, writing a new diary window pops up. So I want to make the code as :
when there’s today’s diary:
show today’s diary

when there isn’t today’s diary:
write today’s diary

How should I change my code? Should I change the whole algorithm?

  • 1

    I don’t understand what you want to do but maybe you need elif. OR simply use print() (and print(type(...)), print(len(...)), etc.) to see which part of code is executed and what you really have in variables. It is called "print debuging" and it helps to see what code is really doing.

    – 

  • when there’s today’s diary What does that mean exactly? Does this mean if a file with a certain name exists?

    – 




  • It means when there’s a file with written time that is today

    – 

This is a long response, so read carefully.

I ran your code by modifying it as below to test it.

There was an error on line 6.

formatted_time = datetime.fromtimestamp( ....

I had to add .date as follows

datetime.date.fromtimestamp( .....

Here is the full code

NOTE: getctime is changed to getmtime

Read below why.

import os
import datetime
from datetime import date

def creation_time_of_files(folder_path, selected_date):
    diary_date_registry = {}
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        print(file_path)

        if os.path.isfile(file_path) and filename.endswith(".txt"):
            creation_time = os.path.getmtime(file_path)
            formatted_time = datetime.date.fromtimestamp(
                creation_time).strftime("%Y-%m-%d")
            print(formatted_time)
            #  Here .date was missing after datetime
            
            if selected_date==date.today().strftime("%Y-%m-%d"):
                if formatted_time==selected_date: 
                     with open(file_path, 'r') as file: #when there's today's diary
                        content = file.read()
                        # file_window = tk.Toplevel(new_window2)
                        # lab = tk.Label(file_window, text=str(content))
                        # lab.pack()
                        print("Opening Existing diary for today")
                    
                elif formatted_time!=selected_date: #there's no today's diary
                    
                    # real_diarypage()
                    print("Let's create new diary")
             
            if selected_date!=date.today().strftime("%Y-%m-%d") and formatted_time==selected_date:
                with open(file_path, 'r') as file:
                    content = file.read()
                    # file_window = tk.Toplevel(new_window2)
                    
                    # lab = tk.Label(file_window, text=str(content))
                    # lab.pack()
                    # return content
                    print("Opening old Diary")
                    print(content)
#  Two files exit in this folder 
#  One .txt file was created today 11/24/2023
#  Another .txt file was created on 9/27/2023 and copied here
creation_time_of_files("D:\\file_date", "2023-11-24")
creation_time_of_files("D:\\file_date", "2023-09-27")

Here are the test cases

CASE: No text file in folder

creation_time_of_files("D:\\file_date", "2023-11-24")

and

creation_time_of_files("D:\\file_date", "2023-09-27")

both print nothing as expected

CASE: New text file for 2023-11-24 is in folder

creation_time_of_files("D:\\file_date", "2023-11-24")

Result: Opening Existing diary for today

This is as expected

creation_time_of_files("D:\\file_date", "2023-09-27")

Result: Nothing is printed

This is as expected

CASE: Only Old text file for 2023-09-27 is in folder

creation_time_of_files("D:\\file_date", "2023-11-24")

Result: Opening Existing diary for today

This is unexpected because the old file was created on 2023-09-24

Change getctime to getmtime

Run again

creation_time_of_files("D:\\file_date", "2023-11-24")

Result: Let’s create new diary

Now this is as expected

Why did getctime —> getmtime help

In Windows here are the file properties for the Oldfile.txt

Old_file_Properties

As you see, the “modified date” corresponds to the 2023-09-24.

You may also want to check this link: getctime and getmtime

Lets run the following

creation_time_of_files("D:\\file_date", "2023-09-27")

Prints : Opening old Diary

This is expected behavior

CASE: Old text file for 2023-09-27 is in folder and so is new text file for today

We keep using getmtime

creation_time_of_files("D:\\file_date", "2023-11-24")

Prints Opening Existing diary for today

This is as expected.

But also prints Let’s create new diary (because of for loop the second file is also processed)

creation_time_of_files("D:\\file_date", "2023-09-27")

Prints: Opening old Diary

So both results are as expected

CASE: Say you modify the old text file ‘today’ then lets see what happens
Now you have a problem because “modified date”, “created date”, “accessed date” all point to “today” = 2023-11-24
Old_File_Properties_After_Changing_And_Saving_Today

SO THERE ARE TWO ISSUES

  1. Using ‘for loop’ and iterating over each file and testing it against conditions may not be best idea. Instead you might want to consider creating a registry dictionary and then just picking the correct file.

Example:

import os
import datetime
from datetime import date

def creation_time_of_files(folder_path, selected_date):
    # Make a registry
    diary_date_registry = {}
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path) and filename.endswith(".txt"):
            creation_time = os.path.getmtime(file_path)
            formatted_time = datetime.date.fromtimestamp(creation_time).strftime("%Y-%m-%d")
            # Store the information
            # key = date
            # value = file path
            diary_date_registry[formatted_time] = file_path
    
    # Get a file by date
    diary_of_interest = diary_date_registry[selected_date]
    # Process that diary as needed
    # You may want to add code for cases when the diary does not exist
    with open(diary_of_interest, 'r') as file: #when there's today's diary
       content = file.read()
       print(content)
       

creation_time_of_files("D:\\file_date", "2023-11-24")
# Prints contents of file with date stamp = "2023-11-24"
creation_time_of_files("D:\\file_date", "2023-09-27") # Notice you have to use 09 and not 9
# Prints contents of this other file
  1. Now the second problem is that the dates will change if you let the user of your diary save the ‘old diary’ on a different day. So either you don’t let them change it on a different date, or you somehow store the date when the diary is created rather than relying on “time stamps”. You could do that within the diary as its first line. The problem is you will have to open each diary and read the “date” from it. After reading you can still store the information in the “registry”. You may want to think more on how you want to do this part.

Suggestions

1) You may want to put the date of creation in the name of textfile. Then you don’t have to open the file.

For example name the files as: month_date_year.txt

11_24_2023.txt

2) Or you could save the names of file and dates they were originally created in a separate file (like txt or json) and simply read this file to populate the registry dictionary in the above code.

I hope this was helpful.

Leave a Comment