Search code examples
pythonfilecopypolling

python script to poll a folder continuously after a certain time interval and copy the new files to another location


I want to poll a folder continuously for any new files, lets say every 1 hours and whenever it finds a new file, it copies to a specific location. I found code to find latest file and to copy to another location. How do I merge this two to get the above desired result? This also may be helpful How to get the most recent file


Solution

  • For polling, the simplest solution is time.sleep(n) which sleeps for n seconds. Your code would look something like this, then:

    import time.sleep as sleep
    import sys
    
    try:
        while True:
            # code to find the latest file
    
            # code to copy it to another location
    
            sleep(3600)
    except KeyboardInterrupt:
        print("Quitting the program.")
    except:
        print("Unexpected error: "+sys.exc_info()[0])
        raise
    

    (Because this loop can run forever, you should definitely wrap it in a try/except block to catch keyboard interrupts and other errors.) Cron jobs are a perfectly good option if you're only going to be on *nix platforms, of course, but this provides platform independence.