How do I check file modified in python as a boolean, so I can implement in IF Statement?

Question:

Im trying to create a function where if file modified, then perform task. I am able to do this if a file exists by doing –

import os
file_path = 'C:/Hi/'
if os.listdir(file_path):
  do xyz

But how can i do xyz based on if a files date was modified?

os.path.getmtime(file_path)

Only gets the time but cant be used in my if statement

Asked By: Jay Janardhan

||

Answers:

Try:

import os 
import time
no_of_seconds_since_last_check = 30
if time.time() - os.path.getmtime(file_path) < no_of_seconds_since_last_check : 
    print("doing xyz")

The if condition detects a file modification within the specified time span, preferably since the last check for modifications.

Answered By: Claudio

Try This Maybe This You want:

import os
from time import sleep
folder_path = r'C:/Hi/'

def check_if_modifed(files : list , data):

    while True:
        sleep(2)
        for file in files:

            last_modifed = os.path.getatime(file)
            if last_modifed != data[file]:


                print(f'{file} Modfied !')

                data[file] = last_modifed
                
if os.listdir(folder_path):
  

    files = os.listdir(folder_path)

    current_data = {}
    for file in files:


        current_data [file] = os.path.getatime(file)

    try:

        check_if_modifed(files , current_data)
    except:

        print('Program Finish!')
Answered By: Kakarotto
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.