Search code examples
pythonif-statementpathlistdir

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


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


Solution

  • 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.