3

I need to set up a script that watches a folder for files of a certain type. Ive made this code but i was wondering if there is a better way?

import os


def listAppleseedFiles(directory_path):
    directory_entities =  os.listdir(directory_path)
    files = []
    appleseed_files = []
    for entity in directory_entities:
        file_path = os.path.join(directory_path, entity)
        if os.path.isfile(file_path):
            if os.path.splitext(file_path)[1] == '.appleseed':
                appleseed_files.append(file_path)

    return appleseed_files

while True:
    for file in listAppleseedFiles('/dir_name'):

        doSomething()
jonathan topf
  • 7,897
  • 17
  • 55
  • 85
  • possible duplicate of [How do I watch a file for changes using Python?](http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python) –  Aug 09 '12 at 11:26

2 Answers2

5

Try Watchdog! From their examples:

import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path='/dir_name', recursive=True)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()
Manuel Ebert
  • 8,429
  • 4
  • 40
  • 61
0

I have used watcher from PyPi successfully, it is a wrapper around the API ReadDirectoryChangesW. Here is an example (Py3, but it runs on Py2):

from watcher import *
import time

def callback(*stuff):
    if stuff[0] == FILE_ACTION_REMOVED:
        print(stuff[1],"deleted")
    else:
        print(stuff)

w = Watcher('C:\\' , callback)
w.flags = FILE_NOTIFY_CHANGE_FILE_NAME
w.start()

while True:  
    time.sleep(100)
cdarke
  • 42,728
  • 8
  • 80
  • 84