I am trying to write a script that monitors a folder, and if the folder has a file added to it, process the file then move it to a DONE folder.
I think I want to use a while loop for this... I will monitor the folder with something like:
count = len(os.listdir('/home/lou/Documents/script/txts/'))
while (count = 1):
print Waiting...
I want the script to check the len() every 30 seconds and if it changes from 1 to 2, run the script, otherwise wait onther 30 seconds and check the len(). The script will move the new file to a folder and the len() will return to 1. The script will run 24/7.
any help is greatly appreciated
thanks
lou
Depending on the size of the directory, it may be best to only check the number of file if the mtime of the directory has changed. If you are using Linux, you may also be interested in inotify.
import sys
import time
import os
watchdir = '/home/lou/Documents/script/txts/'
contents = os.listdir(watchdir)
count = len(watchdir)
dirmtime = os.stat(watchdir).st_mtime
while True:
newmtime = os.stat(watchdir).st_mtime
if newmtime != dirmtime:
dirmtime = newmtime
newcontents = os.listdir(watchdir)
added = set(newcontents).difference(contents)
if added:
print "Files added: %s" %(" ".join(added))
removed = set(contents).difference(newcontents)
if removed:
print "Files removed: %s" %(" ".join(removed))
contents = newcontents
time.sleep(30)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With