最佳实践 - 什么是观看目录的最佳方式

时间:2012-08-09 11:24:27

标签: python directory watch

我需要设置一个脚本来监视某个类型的文件的文件夹。我做了这个代码,但我想知道是否有更好的方法?

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()

2 个答案:

答案 0 :(得分:5)

试试Watchdog!从他们的例子:

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()

答案 1 :(得分:0)

我已经成功使用了PyPi中的watcher,它是API ReadDirectoryChangesW的包装器。这是一个例子(Py3,但它在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)