D3l*_*ato 4 python while-loop wait
我正在尝试编写一个监视文件夹的脚本,如果该文件夹中添加了一个文件,则处理该文件,然后将其移动到DONE文件夹.
我想我想使用while循环...我会用以下内容监视文件夹:
count = len(os.listdir('/home/lou/Documents/script/txts/'))
while (count = 1):
print Waiting...
Run Code Online (Sandbox Code Playgroud)
我希望脚本每隔30秒检查一次len(),如果它从1变为2,则运行脚本,否则等待30秒并检查len().该脚本将新文件移动到一个文件夹,len()将返回1.脚本将全天候运行.
任何帮助是极大的赞赏
谢谢
娄
根据目录的大小,如果目录的mtime已更改,则最好只检查文件的数量.如果您使用的是Linux,您可能也对inotify感兴趣.
import sys
import time
import os
watchdir = '/home/lou/Documents/script/txts/'
contents = os.listdir(watchdir)
count = len(watchdir)
dirmtime = os.stat(watchdir).st_mtime
while True:
newmtime = os.stat(watchdir).st_mtime
if newmtime != dirmtime:
dirmtime = newmtime
newcontents = os.listdir(watchdir)
added = set(newcontents).difference(contents)
if added:
print "Files added: %s" %(" ".join(added))
removed = set(contents).difference(newcontents)
if removed:
print "Files removed: %s" %(" ".join(removed))
contents = newcontents
time.sleep(30)
Run Code Online (Sandbox Code Playgroud)