Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop to monitor folder and run script if conditon is true

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

like image 789
D3l_Gato Avatar asked Feb 22 '23 05:02

D3l_Gato


1 Answers

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)
like image 88
jordanm Avatar answered Apr 06 '23 07:04

jordanm