Skip to content

Instantly share code, notes, and snippets.

@shivshank
Created October 10, 2015 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivshank/25a63f802874c876e252 to your computer and use it in GitHub Desktop.
Save shivshank/25a63f802874c876e252 to your computer and use it in GitHub Desktop.
Monitor new files in a directory for changes.
####
# Monitor new files in a directory for changes.
####
import os, time
# basic ideas from here:
# http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html#poll_with_listdir
dir = "."
originals = os.listdir(dir)
monitoring = {}
while True:
time.sleep(4)
print("checking...")
current = os.listdir(dir)
for f in current:
lastMod = os.path.getmtime(os.path.join(dir, f))
# see if anything is new
if f not in originals:
if f not in monitoring.keys():
print("Found new file:", f)
elif lastMod > monitoring[f]:
print("There was an update in:", f)
# will add f if it's new and record the most recent update time
monitoring[f] = lastMod
# check for missing files (they must've been deleted
for f in list(monitoring):
# we need to use a copy so we can modify the object while iterating
if f not in current:
del monitoring[f]
print(f, "was deleted.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment