Python 在目录轮询的子目录中搜索特定文件

Python 在目录轮询的子目录中搜索特定文件,python,python-2.7,Python,Python 2.7,我是Python的初学者,已经寻找答案有一段时间了,但没有人能解决 目前,我正在编写脚本,使用目录轮询扫描路径中的目录和子目录更改。如果目录中发生新的更改(在本例中是文件夹),它应该能够深入扫描子目录并扫描其中的特定扩展名文件(在本例中是.txt文件)。此代码不起作用,它认为问题始于脚本要扫描添加的文件夹时,并进入文件夹中搜索.txt文件 import os, time import glob path_to_watch="C:\Temp" before=dict ([(f,None) for

我是Python的初学者,已经寻找答案有一段时间了,但没有人能解决

目前,我正在编写脚本,使用目录轮询扫描路径中的目录和子目录更改。如果目录中发生新的更改(在本例中是文件夹),它应该能够深入扫描子目录并扫描其中的特定扩展名文件(在本例中是.txt文件)。此代码不起作用,它认为问题始于脚本要扫描添加的文件夹时,并进入文件夹中搜索.txt文件

import os, time
import glob

path_to_watch="C:\Temp"
before=dict ([(f,None) for f in os.listdir(path_to_watch)])

x=1
while x==1:
    time.sleep(5) #snooze time for each loop iteration
    after = dict ([(f,None) for f in os.listdir(path_to_watch)])
    added = [f for f in after if not f in before]

    if added:
        for path, dirs, files in os.walk(added):
        new_dir=os.path.dirname(os.path.dirname(added))
        for root, dirs, files in os.walk(new_dir):
            for name in files:
                if name.endswith((".txt")):
                    print "Clear"
    before=after