2012-08-09 2 views
3

특정 유형의 파일을 폴더에서 감시하는 스크립트를 설정해야합니다. 필자는이 코드를 만들었지 만 더 좋은 방법이 있는지 궁금해하고 있었습니까?모범 사례 - 디렉토리를 보는 최선의 방법은 무엇입니까?

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

가능한 중복 http://stackoverflow.com/questions/182197/how -do-i-watch-a-file-for-changes-python 사용) –

답변

5

시도 Watchdog! 자신의 예에서 : 나는 성공적으로 PyPi에서 watcher을 사용했다

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

,이 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) 
[? 내가 파이썬을 사용하여 변경 파일을보고 어떻게] (의