0

Within a script is a watcher algorithm which I've adapted from here: https://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory

My aim is now to add a few lines to grab the name of any file that's modified so I can have an if statement checking for a certain file such as:

if [modified file name] == "my_file":
    print("do something")

I don't have any experience with watchdog or file watching so I am struggling finding an answer for this. How would I receive the modified file name?

Fabián Montero
  • 1,613
  • 1
  • 16
  • 34
Colleen
  • 143
  • 1
  • 3
  • 14
  • Related: https://stackoverflow.com/questions/6035263/how-to-use-python-to-search-for-file-by-name-find-the-latest-modified-find-nex – colidyre Aug 30 '18 at 14:14

1 Answers1

1

Current setup of the watchdog class is pretty useless since it just prints...it doesn't return anything.

Let me offer a different approach:

following would get you list of files modified in past 12 hours:

result = [os.path.join(root,f) for root, subfolder, files in os.walk(my_dir) 
            for f in files 
            if dt.datetime.fromtimestamp(os.path.getmtime(os.path.join(root,f))) > 
            dt.datetime.now() - dt.timedelta(hours=12)]

in stead of fixed delta hours, you can save the last_search_time and use it in subsequent searches.

You can then search result to see if it contains your file:

if my_file in result:
    print("Sky is falling. Take cover.")
VanTan
  • 617
  • 4
  • 12